Mutuelinvestor
Mutuelinvestor

Reputation: 3538

How do you limit what text is used to match a regular expression

I have written the following regular express:

(^(?=.*?\bran\b)(?=.*?\bfast\b)[^,]*)

My objective if for it to match the target string when the text up to the first comma includes both ran and fast.

Target Strings:

  1. Jim ran fast, but did win the race => Should match
  2. Jim ran well, but John ran fast too. => Should NOT match
  3. Jim ran well, John ran fast, and Jane ran fast. => Should NOT match

Here is a working sample at regex101

I'm using the pcre (php)

The problem I'm having is that a currently written the regular express is looking at the whole text string to see if the two words (ran and fast) are present. I want to limit the text to the text up to the first comma, but don't know how to achieve this.

Upvotes: 0

Views: 40

Answers (1)

41686d6564
41686d6564

Reputation: 19641

You just need to replace the . instances with [^,] because .*? will include commas, and therefore match any "ran" or "fast" that comes after the comma. Here:

(^(?=[^,]*?\bran\b)(?=[^,]*?\bfast\b)[^,]*)

Regex101 demo.

Be aware that [^,] will also match new line, so if that's not what you want, you might consider using something like [^,\n] or [^,\r\n].

Also, note that your regex will match even if there are no commas. If you want to make sure your match is followed by a comma, you might need to add another positive Lookahead at the end (i.e., (?=,)).

Upvotes: 2

Related Questions