stevemao
stevemao

Reputation: 1483

Regex to match keywords followed by anything but stop at the next keywords

I want to match ThisAnything and ThatAnything (two matches) in ThisAnthingThatAnything

So far I've got /(?:This|That)(?:.*)/g but this will match ThisAnthingThatAnything (one match but I want two). How do I achieve this? Thanks

Upvotes: 0

Views: 57

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

Use positive lookahead and capture the two substrings in 2 groups:

(This.*?(?=This|That|\b)|That.*?(?=This|That|\b))

See example.

Result:

MATCH 1
1.  [0-11]  `ThisAnthing`
MATCH 2
1.  [11-23] `ThatAnything`

Upvotes: 1

georg
georg

Reputation: 214959

split(/(?=This|That)/g) should do the trick:

s = "ThisAnthingThatAnythingThatMoreThisMore"

a = s.split(/(?=This|That)/g)
document.write(a)

Upvotes: 1

beerbajay
beerbajay

Reputation: 20270

You want a reluctant quantifier, *?; so your regex becomes (This|That)(.*?)

Upvotes: 0

Related Questions