cycle4passion
cycle4passion

Reputation: 3331

Regex: capture group of max number of sequential defined words

regex: cat|dog|mouse|fish

on

text: dog cat

captures a group with 2 matches. I would like a group with a single match of "dog cat".

I tried [cat|dog|mouse|fish]+ but still 2 matches, and also matches other things?

Upvotes: 2

Views: 62

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174816

Add an optional \s or \s* before the pattern and make it to repeat one or more times.

\b(?:\s?(?:cat|dog|mouse|fish))+

[cat|dog|mouse|fish] is the wrong way of matching group of characters. You need to put those substrings inside a group not inside a character class.

DEMO

OR

(?<nnn>\b(?:cat|dog|mouse|fish)(?:\s+(?:cat|dog|mouse|fish)\b)*)

DEMO

Upvotes: 3

Related Questions