Remove everything in parentheses java using regex

前端 未结 7 1016
忘掉有多难
忘掉有多难 2020-12-16 20:01

I\'ve used the following regex to try to remove parentheses and everything within them in a string called name.

name.replaceAll(\"\\\\(.*\\\\)\"         


        
相关标签:
7条回答
  • 2020-12-16 20:27

    To get around the .* removing everything in between two sets of parentheses you can try :

    name = name.replaceAll("\\(?.*?\\)", "");
    
    0 讨论(0)
  • 2020-12-16 20:31

    Strings are immutable. You have to do this:

    name = name.replaceAll("\\(.*\\)", "");
    

    Edit: Also, since the .* is greedy, it will kill as much as it can. So "(abc)something(def)" will be turned into "".

    0 讨论(0)
  • 2020-12-16 20:33

    String.replaceAll() doesn't edit the original string, but returns the new one. So you need to do:

    name = name.replaceAll("\\(.*\\)", "");
    
    0 讨论(0)
  • 2020-12-16 20:33

    I'm using this function:

    public static String remove_parenthesis(String input_string, String parenthesis_symbol){
        // removing parenthesis and everything inside them, works for (),[] and {}
        if(parenthesis_symbol.contains("[]")){
            return input_string.replaceAll("\\s*\\[[^\\]]*\\]\\s*", " ");
        }else if(parenthesis_symbol.contains("{}")){
            return input_string.replaceAll("\\s*\\{[^\\}]*\\}\\s*", " ");
        }else{
            return input_string.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");
        }
    }
    

    You can call it like this:

    remove_parenthesis(g, "[]");
    remove_parenthesis(g, "{}");
    remove_parenthesis(g, "()");
    
    0 讨论(0)
  • 2020-12-16 20:34

    As mentionend by by Jelvis, ".*" selects everything and converts "(ab) ok (cd)" to ""

    The version below works in these cases "(ab) ok (cd)" -> "ok", by selecting everything except the closing parenthesis and removing the whitespaces.

    test = test.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");
    
    0 讨论(0)
  • 2020-12-16 20:47

    In Kotlin we must use toRegex.

    val newName = name.replace("\\(?.*?\\)".toRegex(), "");
    
    0 讨论(0)
提交回复
热议问题