Raja
Raja

Reputation: 3627

Regex match two words or at least one

I have a problem with my regex string. I have two combinations of strings as follows,

2.3.8.2.2.1.2.3.4.12345 = WORDS: "String to capture"
2.3.8.2.2.1.2.3.4.12345 = ""

Regex:

1\.2\.3\.4\.(\d+) = WORDS: (?|"([^"]*)|([^:]*))

https://regex101.com/r/kQ3wT5/10 - matching

https://regex101.com/r/kQ3wT5/9 - Not matching

This regex is matching only for the first string and not for the second where i have empty string. So the regex has to match on both scenario. And one more thing I really don't want to go with "global" match.

Upvotes: 2

Views: 1773

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You need to make WORDS:<space> optional by enclosing it with an optional non-capturing group:

1\.2\.3\.4\.(\d+) = (?:WORDS: )?(?|"([^"]*)|([^:]*))

See the regex demo.

The (?:WORDS: )? matches 1 or 0 sequences (due to the ? quantifier) of WORDS: substring followed with a space.

Upvotes: 1

Related Questions