简体   繁体   English

如何使用Java的String.replaceAll方法替换加号字符

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

What's the correct regex for a plus character (+) as the first argument (ie the string to replace) to Java's replaceAll method in the String class? 加号字符(+)的正确正则表达式是String类中Java的replaceAll方法的第一个参数(即要替换的字符串)是什么? I can't get the syntax right. 我无法正确理解语法。

You need to escape the + for the regular expression, using \\ . 你需要使用\\来转义正则表达式的+

However, Java uses a String parameter to construct regular expressions, which uses \\ for its own escape sequences. 但是,Java使用String参数来构造正则表达式,该表达式使用\\来表示自己的转义序列。 So you have to escape the \\ itself: 所以你必须逃避\\本身:

"\\+"

如果有疑问,让java为你做的工作:

myStr.replaceAll(Pattern.quote("+"), replaceStr);

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 \\. 你需要用\\来转义+,因为\\本身是Java字符串中的一个特殊字符,你需要用另一个\\来转义它。

So your regex string will be defined as "\\\\+" in Java code. 因此,您的正则表达式字符串将在Java代码中定义为“\\\\ +”。

Ie this example: 即这个例子:

String test = "ABCD+EFGH";
test = test.replaceAll("\\+", "-");
System.out.println(test);

Others have already stated the correct method of: 其他人已经说过正确的方法:

  1. Escaping the + as \\\\+ +转义为\\\\+
  2. Using the Pattern.quote method which escapes all the regex meta-characters. 使用Pattern.quote方法,它可以转义所有正则表达式元字符。

Another method that you can use is to put the + in a character class. 您可以使用的另一种方法是将+放在一个字符类中。 Many of the regex meta characters ( . , * , + among many others) are treated literally in the character class. 许多正则表达式元字符( .*+等等)都在字符类中进行字面处理。

So you can also do: 所以你也可以这样做:

orgStr.replaceAll("[+]",replaceStr);

Ideone Link Ideone Link

如果你想要一个简单的字符串查找和替换(即你不需要正则表达式),使用Apache Commons中StringUtils可能会更简单,这可以让你写:

mystr = StringUtils.replace(mystr, "+", "plus");

假设您要替换-使用\\\\\\- ,请使用:

 text.replaceAll("-", "\\\\\\\\-");
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);

How about replacing multiple '+' with an undefined amount of repeats? 如何用不确定的重复次数替换多个'+'?

Example: test+test+test+1234 示例:test + test + test + 1234

(+) or [+] seem to pick on a single literal character but on repeats. (+)或[+]似乎选择单个文字字符,但重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM