简体   繁体   English

用'*'替换全部

[英]replaceAll with '*'

replaceAll with a value that contains '*' is throwing an exception. 包含“ *”的值的replaceAll引发异常。

I tried this 我试过了

String tmp = "M ******* k";

tmp = tmp.replaceAll("****","NOT");

System.out.println("TMP is :"+tmp);

and I am getting this exception 我得到这个例外

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

Why does replaceAll with * have this behavior and how do I overcome with this problem? 为什么用*替换replaceAll出现这种现象,我该如何克服呢?

The first argument in replaceAll() takes a regular expression. replaceAll()中的第一个参数采用正则表达式。 The character '*' has a special meaning in regular expressions. 字符“ *”在正则表达式中具有特殊含义。

Replaces each substring of this string that matches the given regular expression with the given replacement. 用给定的替换项替换该字符串中与给定的正则表达式匹配的每个子字符串。

So you have to escape it, if you want to match the literal character '*'. 因此,如果要匹配文字character '*'. ,则必须对其进行转义character '*'.

Use "\\\\*". 使用"\\\\*".

oracle forum on the same 甲骨文论坛在同一

You can check this code for reference: 您可以检查以下代码以供参考:

 public static void main (String[] args) 
    {
          String tmp = "M ******* k";

          tmp = tmp.replaceAll("\\*","NOT");

          System.out.println("TMP is :"+tmp);
    }

'*' is regular expression special char in java.So you need to follow rules of regular expressions. *是Java中的正则表达式特殊字符,因此您需要遵循正则表达式的规则。

http://docs.oracle.com/javase/tutorial/essential/regex/quant.html http://docs.oracle.com/javase/tutorial/essential/regex/quant.html

Try 尝试

tmp = tmp.replaceAll("\\*+","NOT");

More ; 更多 ;

尝试转义* s:

tmp = tmp.replaceAll("\\*\\*\\*\\*","NOT");
tmp = tmp.replace("****","NOT"); // No regular expression
tmp = tmp.replaceAll("\\*\\*\\*\\*","NOT");

The second alternative is the regular expression one. 第二种选择是正则表达式。

Have you tried escaping the asterisks? 您是否尝试过将星号转义? As the PatternSyntaxException points out, * is a special character which requires a character class before it. 正如PatternSyntaxException指出的, *是一个特殊字符,在其之前需要一个字符类。

More appropriate way to do it would be: 更合适的方法是:

tmp = tmp.replaceAll("\\*\\*\\*\\*", "NOT");

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

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