0

I have cool regex from here Regex to match string containing two names in any order

^(?=.*\bjack\b)(?=.*\bjames\b).*$

But I need substring as result.

For example:


  • hi jack here is james whats up
  • I need as result jack here is james

  • hi james here is jack whats up
  • I need as result james here is jack

I cannot use jack or james in regex more than 1 time.

How can I get it?

Diggy
  • 115
  • 8

2 Answers2

2

You could just use an alternation here:

^.*\b(jack\b.*\bjames|james\b.*\bjack)\b.*$

Demo

In this case, the content you want to match would appear in the first capture group, q.v. the demo link above.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Sorry, I did not add important condition. I cannot use jack or james in regex more than 1 time. It's long story why it's so. But I really need this condition. Could help me with that? – Diggy Jan 13 '20 at 16:45
  • I can't imagine why you have that requirement. Can you elaborate? – Tim Biegeleisen Jan 13 '20 at 16:48
  • OK, if you have time to listen to :) I have test which uses regex as expected result. Some check calculates how many 'jack' or 'james' should be found in log and then compare it with actual result, I mean real log of real test run. So if I add in regex one more 'jack' then check will expect one more 'jack' in real log. But in real log there will not be any additional 'jack' and test will be failed. – Diggy Jan 13 '20 at 16:55
0
/j[ack|ames]+ here is j[ack|ames]+/g

re = /j[ack|ames]+ here is j[ack|ames]+/g

let arr = [
    "hi jack here is james whats up",
    "hi james here is jack whats up"
]

console.log(arr.map(str => str.match(re)[0]))
symlink
  • 11,984
  • 7
  • 29
  • 50