[regexp] Look Around

zion·2023년 11월 5일
0

프론트엔드

목록 보기
5/8
💡 html 코드에서 html tag 를 제외한 <, > 문자를 검색하는 정규표현식을 찾던 중 Look Around 에 대해 정리한다.
  • Look Around 는 매치되는 문자의 전후문자에 조건을 추가하는 부분으로, 매치 결과에 포함되지 않는다.
  • 중첩을 허용한다. 두 조건이 존재할 경우, 두 조건 모두 일치해야 매칭된다.

Look Around 종류

  • Lookahead
  • Negative lookahead
  • Lookbehind
  • Negative lookbehind

Lookahead x(?=y)
: 뒤에 y로 이어지는 x를 매칭한다.

let str = "1 turkey costs 30€";
alert( str.match(/\d+(?=€)/)); //30

Negative Lookahead x(?!y)
: 뒤에 y로 이어지지 않는 x를 매칭한다.

let str = "1 turkey costs 30€";
alert( str.match(/\d+(?!€)/)); //1

Lookbehind (?<=y)x
: 앞에 y로 이어진 x를 매칭한다.

let str = "1 turkey costs $30";
alert( str.match(/(?<=\$)\d+/)); // 30

Negative Lookbehind (?<!y)x
: 앞에 y로 이어지지 않은 x를 매칭한다.

let str = "1 turkey costs $30";
alert( str.match(/(?<!\$)\d+/)); // 1

Lookbehind는 Safari, Internet Explorer와 같은 V8이 아닌 브라우저에서는 지원되지 않는다.

https://javascript.info/regexp-lookahead-lookbehind

profile
be_zion

0개의 댓글