How to remove a pattern that may or may not exist at the end using regex

前端 未结 1 1071
感情败类
感情败类 2021-01-25 08:54

I want to capture without including a certain pattern (anything in parenthesis) that may or may not exist at the end of the string. I want to capture everything but the string \

相关标签:
1条回答
  • 2021-01-25 09:45

    You may use your matching approach with

    ^(.+?)(?:\(.*\))?$
    

    See the regex demo. Basically, you need to add anchors to your pattern and use a lazy quantifier with the first dot matching pattern.

    Details

    • ^ - start of the string
    • (.+?) - Group 1: one or more chars other than newline as few as possible (*? allows the regex engine to test the next optional subpattern first, and only expand this one upon no match)
    • (?:\(.*\))? - an optional sequence of
      • \( - a ( char
      • .* - any 0+ chars other than newline as many as possible
      • \) - a ) char
    • $ - end of string.

    In C#:

    var m = Regex.Match(s, @"^(.+?)(?:\(.*\))?$");
    var result = string.Empty;
    if (m.Success) {
        result = m.Groups[1].Value;
    }
    

    You may also remove a substring in parentheses at the end of the string if it has no other parentheses inside using

    var res = Regex.Replace(s, @"\s*\([^()]*\)\s*$", "");
    

    See another demo. Here, \s*\([^()]*\)\s*$ matches 0+ whitespaces, (, any 0+ chars other than ( and ) ([^()]*) and then 0+ whitespaces at the end of the string.

    0 讨论(0)
提交回复
热议问题