0

What is the difference between the below two expressions? 1. (\S+) 2. (\S+?)

I would appreciate if someone could explain this.

Thanks,

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Kavitha
  • 155
  • 3
  • 12
  • 1
    https://regex101.com/ based on a quick test I ran here, `(\S+)` is going to find you whole words, and `(\S+?)` is going to find you individual characters. I'm not confident enough in my answer to post it as an actual answer though. – phroureo Sep 20 '17 at 20:14
  • 1
    See https://stackoverflow.com/questions/25528452/in-a-regex-what-changes-when-you-add-a-question-mark-to – Tzach Zohar Sep 20 '17 at 20:14

1 Answers1

1

The first means match a single character that is a non-whitespace character, between one and unlimited times, as many times as possible, giving back as needed (greedy).

The second means Match a single character that is a non-whitespace character, between one and unlimited times, as few times as possible, expanding as needed (lazy).

The difference is greedy or lazy repetition. From the Regex Buddy help file:

A greedy quantifier will first try to repeat the token as many times as possible, and gradually give up matches as the engine backtracks to find an overall match. A lazy quantifier will first repeat the token as few times as required, and gradually expand the match as the engine backtracks through the regex to find an overall match.

The differences can be seen in the images below:

Greedy quantifier

Lazy quantifier

Ken White
  • 117,855
  • 13
  • 197
  • 405