How to replace a plus character using Java's String.replaceAll method

后端 未结 8 1793
别跟我提以往
别跟我提以往 2020-12-28 11:50

What\'s the correct regex for a plus character (+) as the first argument (i.e. the string to replace) to Java\'s replaceAll method in the String class? I can\'t

相关标签:
8条回答
  • 2020-12-28 12:19

    Say you want to replace - with \\\-, use:

     text.replaceAll("-", "\\\\\\\\-");
    
    0 讨论(0)
  • 2020-12-28 12:28

    You'll need to escape the + with a \ and because \ is itself a special character in Java strings you'll need to escape it with another \.

    So your regex string will be defined as "\\+" in Java code.

    I.e. this example:

    String test = "ABCD+EFGH";
    test = test.replaceAll("\\+", "-");
    System.out.println(test);
    
    0 讨论(0)
  • 2020-12-28 12:29

    If you want a simple string find-and-replace (i.e. you don't need regex), it may be simpler to use the StringUtils from Apache Commons, which would allow you to write:

    mystr = StringUtils.replace(mystr, "+", "plus");
    
    0 讨论(0)
  • 2020-12-28 12:32

    when in doubt, let java do the work for you:

    myStr.replaceAll(Pattern.quote("+"), replaceStr);
    
    0 讨论(0)
  • 2020-12-28 12:33

    How about replacing multiple ‘+’ with an undefined amount of repeats?

    Example: test+test+test+1234

    (+) or [+] seem to pick on a single literal character but on repeats.

    0 讨论(0)
  • 2020-12-28 12:34
    String str="Hello+Hello";   
    str=str.replaceAll("\\+","-");
    System.out.println(str);
    

    OR

    String str="Hello+Hello";   
    str=str.replace(Pattern.quote(str),"_");
    System.out.println(str);
    
    0 讨论(0)
提交回复
热议问题