Skip to content

Instantly share code, notes, and snippets.

@hongry18
Last active June 2, 2022 03:04
Show Gist options
  • Save hongry18/6ccf4d44cb0420cd6b9673e47cf08168 to your computer and use it in GitHub Desktop.
Save hongry18/6ccf4d44cb0420cd6b9673e47cf08168 to your computer and use it in GitHub Desktop.

Regular Expression

Lookahead & Lookbehind

positive Lookahead

positive lookahead는 a다음 b가 오도록 한다.

var reg = /a(?=b)/g;

negative Lookahead

negative lookahead는 a다음 b가 아니도록 한다.

var reg = /a(?!b)/g;

positive Lookbehind

var reg = /(?<=b)a/g;

negative Lookbehind

var reg = /(?<!b)a/g;

example) html 마크업 내부의 text를 얻어올떄

var reg = /(?<=<tag>).*(?=<\/tag>)/m
var matchs = reg.exec('<tag>zxcv</tag>')
console.log(matchs)

example) 긴 숫자 타입에 콤마를 삽입할때 replace 위치 찾을때.

'1259127321420'.replace(/(-?\d)(?=(\d{3})+$)/g, '$1,')
'1259127321420'.replace(/(?=(\d{3})+(?!\d))/g, ',')

capture

capturing

group1: capture
group2: character

var reg = /(capture)(character)/m
var matchs = reg.exec('capturecharacter')
console.log(matchs)

non-capturing

group1: character

var reg = /(?:capture)(character)/m
var matchs = reg.exec('capturecharacter')
console.log(matchs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment