How to remove a possibly parenthesized expression from a string?

后端 未结 1 874
独厮守ぢ
独厮守ぢ 2021-01-25 14:34

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

相关标签:
1条回答
  • 2021-01-25 15:18

    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).
    0 讨论(0)
提交回复
热议问题