3

I understand that ? can be used to make modifiers only match the first occurence and prevent the greediness, but maybe I've misunderstood how it's supposed to work. If the string is:

one two three four four four five six

...and I want to capture three. I've been trying:

^one two (.*)(four)+?.*$

...but this gives me three four four. What am I doing wrong? I've tried ?? and .? and just (four)?, but it's not working.

Sandeep Chatterjee
  • 3,110
  • 7
  • 25
  • 44
RTF
  • 5,332
  • 8
  • 47
  • 104

3 Answers3

6

Just do this:

^one two (.*?) four.*$

Or you can use \S which means non whitespace characters,

^one two (\\S+) four.*$
Sabuj Hassan
  • 35,286
  • 11
  • 68
  • 78
3

If you want to capture three you can simply do:

^one two (\w+) four
anubhava
  • 664,788
  • 59
  • 469
  • 547
1

This:

^one two (.*)(four)+?.*$

means match one two and then, as much as possible (.*), until you see a four, repeatedly, followed by arbitrary characters.

Possibly you would be better off with splitting this string on white space and inspecting the words ("one",...).

laune
  • 30,276
  • 3
  • 26
  • 40