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,200
  • 7
  • 29
  • 47
RTF
  • 5,780
  • 8
  • 54
  • 119

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
  • 36,940
  • 12
  • 73
  • 83
3

If you want to capture three you can simply do:

^one two (\w+) four
anubhava
  • 713,503
  • 59
  • 514
  • 593
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,694
  • 3
  • 27
  • 41