What is the meaning of + in a regex?

Viewed 56663

What does the plus symbol in regex mean?

5 Answers

A lot depends on where + symbol appears and what the regex flavor is.

In and (in a non-very magic mode) flavor, + matches a literal + char. E.g. sed 's/+//g' file > newfile removes all + chars in file. If you want to use + as a quantifier here, use \+ (supported in GNU tools), or replace with \{1,\} or double the quantified pattern and remove the quantifier from the first part and add * (zero or more occurrences quantifier) after the other (e.g. sed 's/c++*//' removes c followed with one or more + chars).

In and other regex flavors, outside a character class ([...]), + acts as a quantifier meaning "one or more, but as many as possible, occurrences of the quantified pattern*. E.g. in , s.replace(/\++/g, '-') will replace a string like ++++ with a single -. Note that in NFA regex flavors + has a lazy counterpart, +?, that matches "one or more, but as few as possible, occurrences of the quantified pattern".

Inside a character class, the + char is treated as a literal char, in every regex flavor. [+] always matches a single + literal char. E.g. in , Regex.Replace("1+2=3", @"[+]", "-") will result in 1-2=3. Note it is not a good idea to use a single char inside a character class, only use a character class for two or more chars, or for charsets. E.g. [+0-9] matches a + or any ASCII digit chars. In , preg_replace('~[\s+]+~', '-', '1 2+++3') will result in 1-2-3 since the regex matches one or more (due to last + that is a quantifier) whitespaces (\s) or plus chars (+ insdide the character class).

The + symbol can also be a part of the possessive quantifier in some PCRE-like regex flavors (, , , , , etc (but no in re, , ). E.g. C\+++(?!\d) in PCRE would match C and then one or more + symbols (\+ - a literal + and ++ one more occurrences with allowing to backtrack into this quantified pattern) not followed with a digit. If there is a digit after plus chars the whole match fails. Other examples: a?+ (one or zero a chars), a{1,3}+ (one to three a chars as many as possible), a{3}+ (=a{3}, three as), a*+ matches zero or more a chars.

Related