Trace
Trace

Reputation: 18869

regular expression: plus character

Finally started learning some regex.
This is probably a stupid question, but what would be the difference between

tre+ 

and

tre 

If it finds it, it matches, right?

Edit: currently reading this tutorial: http://www.zytrax.com/tech/web/regex.htm

Upvotes: 0

Views: 314

Answers (4)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

tre+ matches tr with one or more a following. tre matches just tre.

If you just check if the string matches, they will match the same strings. The difference starts when you are interested in knowing which part of the string matched. For instance if the entire string matched, or when you want to capture the matched part.

Upvotes: 1

Kent
Kent

Reputation: 195039

you didn't tell which regex flavor you were using.

for BRE (Basic Regular Expressions):

tre+ matches string: "tre+"
tre  matches string: "tre"

for ERE/PCRE (Extended Regular Expressions/Perl Compatible Regular Expressions): Avinash answered it already.

tre+ matches string: "tre" or "tree" or "treeeeeee" 
tre  matches string: "tre"

Upvotes: 1

Barmar
Barmar

Reputation: 780869

The difference may be significant depending on how you're using the regular expression. If you're just testing whether a string matches the regexp, the + is redundant. But if you're using it to perform a substitution, e.g. preg_replace in PHP or s/regexp/replacement/ in Perl or sed, using the + will cause it to replace the longest matching substring.

For example, if your input string is:

Cut down the trees

and you do:

s/tre/foo/

the result will be:

Cut down the fooes

But if you do:

s/tre+/foo/

the result will be:

Cut down the foos

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

  • tre+ Matches tr plus the following one or more e's.

  • tre Matches the string tre

Upvotes: 4

Related Questions