Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression (\S+?) vs (\S+)) [duplicate]

Tags:

regex

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

I would appreciate if someone could explain this.

Thanks,

like image 222
Kavitha Avatar asked Sep 02 '25 10:09

Kavitha


1 Answers

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

like image 121
Ken White Avatar answered Sep 05 '25 02:09

Ken White