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,220
  • 9
  • 31
  • 47
RTF
  • 6,214
  • 12
  • 64
  • 132

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
  • 38,281
  • 14
  • 75
  • 85
3

If you want to capture three you can simply do:

^one two (\w+) four
anubhava
  • 761,203
  • 64
  • 569
  • 643
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
  • 31,114
  • 3
  • 29
  • 42