-2

I want to craft a regex pattern to match any word combination composed of n words

E.g.

I tried to use "(?:\w+\s){2}" to match two-word combinations in the sentence "one two three four "

I only got two matches: "one two " and "three four ".

I expect to also get another match "two three ".

Why the pattern missed it? Is there a way to fix it? JavaScript or .net flavor is preferred.

After some googling, still not find a solution. Many thanks.

  • 1
    see https://stackoverflow.com/questions/11430863/how-to-find-overlapping-matches-with-a-regexp – Phu Ngo Oct 21 '22 at 04:27
  • Regex matches do not overlap, once a char is matched the regex engine moves forward looking for a new match. – Poul Bak Oct 21 '22 at 04:40

1 Answers1

-1

why the pattern missed it?

is answer here How can I match overlapping strings with regex?

and here is a way to fix it:

(?=((\b\w+\b\s){2}))

regex101 example

  • Thanks you all for the informative link. I solved it. Here is the pattern I used: `(?=(\b\w+\s\w+\b))`. My python and .net code snippet could be viewed [here](https://replit.com/@wood9527/re-match-word-combination#main.py) and [there](https://replit.com/@wood9527/re-match-word-combination-1#main.cs). – charlie9527 Oct 22 '22 at 13:41