I want to use RegEx in order to remove version numbers from product names. The names can look like this:
SampleProduct 2.0
They can also have parent
If you want to avoid repeating the part of a pattern in a regex and just want to match 2.0
or (2.0)
BUT not (2.0
or 2.0)
, you may use a conditional regex:
(\()?\d+(?:\.\d+)*(?(1)\))
See the regex demo.
If there is just one parentheses it won't become part of a match.
Details
(\()?
- An optional capturing group #1: a (
char (if there is no (
, the value of this group is null and the later (?(1)...)
check will fail)\d+
- 1 or more digits(?:\.\d+)*
- 0 or more repetitions of .
and 1+ digits(?(1)\))
- a conditional construct: if Group 1 matched, )
must be matched, else there is nothing to match (absent |...)
else condition part means anything can follow the pattern before).