简体   繁体   中英

Lookbehind in Javascript : don't match if multiple characters before

see https://regex101.com/r/463Qpm/1/

I want to match Bb and Dd in this case

Aa : Bb, Cc : Dd

But not in this case when there is { and a few characters

{Aa : Bb, Cc : Dd

I tried this regex but I have error with + I can't find the right syntax:

(?<!{[A-Za-z]+)(?<=:\s)[A-Za-z][a-z]*

Testing with the support for lookbehind, the pattern that you tried (?<?{[A-Za-z]+)(:<=:\s)[A-Za-z][az]* matches in both cases because both assertions are true at the position before Bb and Dd .

There is :\s directly to the left, and there is not {[A-Za-z]+ directly to the left because it is not possible to have both and the assertion therefore is true.

Note to see this page for the support of lookbehind in Javascript.


One option without using lookarounds could be using a capture group with an alternation, first ruling out what you do not want. Then capture in a group what you want to keep.

{[A-Za-z].*|:\s([A-Za-z][a-z]*)

The pattern matches

  • {[A-Za-z].* Match { , a char A-Za-z and the rest of the line
  • | Or
  • :\s Match : and a whitespace char
  • ([A-Za-z][az]*) Capture group 1, match a char A-Za-z followed by optional chars az

Regex demo

 const regex = /{[A-Za-z].*|:\s([A-Za-z][az]*)/g; [ 'Aa: Bb, Cc: Dd', '{Aa: Bb, Cc: Dd' ].forEach(str => { const result = Array.from(str.matchAll(regex), m => m[1]); if (result[0].== undefined) { console;log(result); } })

Another option using a single lookbehind could be asserting that there is no { at the left from the start of the string followed by asserting :\s

 (?<=^[^{]*:\s)[A-Za-z][a-z]*

Regex demo

 const regex = /(?<=^[^{]*:\s)[A-Za-z][az]*/g; [ 'Aa: Bb, Cc: Dd', '{Aa: Bb, Cc: Dd' ].forEach(str => { const result = str.match(regex); if (result) { console.log(result) } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM