How can I replace a string in parentheses using a regex?

前端 未结 4 1052
春和景丽
春和景丽 2020-12-05 18:16

I have a string:

HLN (Formerly Headline News)

I want to remove everything inside the parens and the parens themselves, leaving only:

<
相关标签:
4条回答
  • 2020-12-05 18:43

    You could use the following regular expression to find parentheticals:

    \([^)]*\)
    

    the \( matches on a left parenthesis, the [^)]* matches any number of characters other than the right parenthesis, and the \) matches on a right parenthesis.

    If you're including this in a java string, you must escape the \ characters like the following:

    String regex = "\\([^)]*\\)";
    
    0 讨论(0)
  • 2020-12-05 18:48
    String foo = "(x)()foo(x)()";
    String cleanFoo = foo.replaceAll("\\([^\\(]*\\)", "");
    // cleanFoo value will be "foo"
    

    The above removes empty and non-empty parenthesis from either side of the string.

    plain regex:

    \([^\(]*\)

    You can test here: http://www.regexplanet.com/simple/index.html

    My code is based on previous answers

    0 讨论(0)
  • 2020-12-05 19:02

    Because parentheses are special characters in regexps you need to escape them to match them explicitly.

    For example:

    "\\(.+?\\)"
    
    0 讨论(0)
  • 2020-12-05 19:03
    String foo = "bar (baz)";
    String boz = foo.replaceAll("\\(.+\\)", ""); // or replaceFirst
    

    boz is now "bar "

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