0

I can use one common regex pattern to grab groups from the following two strings

show me light not fear
show me light and grace

Regex: show me ([\w]+) (not ([\w]+)|and ([\w]+))

But I cannot find a common regex for below:

show me light
show me light and grace

Regex: show me ([\w]+)| and ([\w]+)

it treats "and grace" in second string as separate match, Can you please help me identify the mistake

unchained
  • 19
  • 6
  • You need [`show\s+me\s+(\w+)*(?:\s+and\s+(\w+))?`](http://regexstorm.net/tester?p=show%5cs%2bme%5cs%2b%28%5cw%2b%29*%28%3f%3a%5cs%2band%5cs%2b%28%5cw%2b%29%29%3f&i=show+me+light%0d%0ashow+me+light+and+grace) – Wiktor Stribiżew Jul 16 '18 at 22:35

2 Answers2

0

That's because you had it in a separate capture group.

Try something like this

show me (\w+) ?(not|and)? ?(\w+)?

emsimpson92
  • 1,779
  • 1
  • 9
  • 24
  • Thanks it worked!! How does wrapping around with '?' work, as in the one where you used ?(not|and)? – unchained Jul 16 '18 at 22:18
  • I wasn't wrapping it with those. ` ?` was to have an optional space, then `(not|and)?` for an optional not or and, ` ?` for another optional space, and `(\w+)?` for an optional word. I made all of those optional so it would also match "show me light" – emsimpson92 Jul 16 '18 at 22:20
  • Thanks for explaining. Learnt about optional space – unchained Jul 16 '18 at 22:41
0

The alternation operator | has the lowest precedence, so your second example matches either show me ([\w]+) or and ([\w]+).

Here is a regex matching both strings: show me ([\w]+)( and ([\w]+))?