1

Here's the string and the sentence I want to match (extract).

let pigs = "\X The animal 0000 I really dig \X Above all others is the pig. 222 \X Pigs are noble. Pigs are clever 3333, \X Pigs are 5555 courteous.\X However, Now and then, to break this 6666 rule, \X One meets 7777 a pig who is a fool. \X"

" Pigs are 5555 courteous."

Here's two versions of my code. When I check in on various regexp-check websites, it gives the desired match. But when I run in the browser console, it gives null. I have the latest Chrome version. Why doesn't the browser console output the match here?

pigs.match(/(?<=\\X)[^\\X]*5555[^\\X]*(?=\\X)/g);
pigs.match(/(?:\\X)[^\\X]*5555[^\\X]*(?:\\X)/g); 
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

You could use following pattern:

(?<=\X)(?:.(?!\X))+5555.+?(?=\X)

What I changed is: (?:.(?!\X))+ - which is non-capturing group and expression matches one or more characters, which are not followed by \X.

Also, you wrongly used [^\\X] - it's just negated class, it will match any character other than \ or X.

Below JS example:

let pigs = "\X The animal 0000 I really dig \X Above all others is the pig. 222 \X Pigs are noble. Pigs are clever 3333, \X Pigs are 5555 courteous.\X However, Now and then, to break this 6666 rule, \X One meets 7777 a pig who is a fool. \X"

let match = pigs.match(/(?<=\X)(?:.(?!\X))+5555.+?(?=\X)/g)

console.log(match)
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69