0

I have a one long string with sentences, every sentence contains a number. Every sentence is separated by /X. Having a given number, how can I match and extract only the one sentence which contains that number?

"\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"

For example, I want to extract the sentence with the number 5555, to get this: " Pigs are 5555 courteous."

How to do this with JS regexp? My code matches the whole text:

str.match(/\\X.*5555.*\\X/);

1 Answers1

0

You need to make sure to exclude in .* the case when it would match \\X.

This worked for me:

/[^\\X]*5555[^\\X]*/g

Use this if you want to exclude the first space of your sentence, however it requires support for Lookbehind:

/(?<=\\X )[^\\X]*5555[^\\X]*/g
T.Trassoudaine
  • 1,242
  • 7
  • 13
  • The code is working (I checked it on a regexp exercise website and it gives the match I needed), however in Chrome console it doesn't work. I have the latest version of Chrome. Doesn't Chrome support positive lookbehind? – Lukasz Pospiech Sep 15 '21 at 17:49
  • Here the supposed support of Lookbehind: https://caniuse.com/?search=lookbehind – T.Trassoudaine Sep 15 '21 at 21:19