ERROR – 在索引0附近有悬挂的元字符’*’ *1

huangapple go评论83阅读模式
英文:

ERROR - Dangling meta character '*' near index 0 *1

问题

我有一个字符串

`String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";`

我想要替换段落 " *1"。但我失败了

`result.replaceAll("*1", "A");`

如果我使用这个,我会得到错误: `Dangling meta character '*' near index 0
*1`

我正在尝试替换所有的 " *1" 段落,但它给了我一个错误。
英文:

I have a string that is

String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";

I want to replace the segment "*1". But I failed

result.replaceAll("*1", "A");

If I use this I get error : Dangling meta character '*' near index 0
*1

I am trying to replace all the "*1" segment but it gives me error.

答案1

得分: 1

replaceAll()方法的第一个参数是一个正则表达式。
在正则表达式中,* 是一个元字符,用于表示 '零次或多次',例如使用 .*[0-9]*
如果单独使用它,它会被解释为 '纠缠的字符'。要引用 * 字符本身,您需要使用 \ 进行转义,在Java字符串中再次进行转义。

因此,请使用 replaceAll("\\*", "A")

英文:

The replaceAll() method's first parameter is a regular expression.
In regex, the * is a meta character that is used for 'zero or more times' e.g. with .* or [0-9]*.
Used by itself it is 'tangling'. To reference the * character itself, you need to escape it with \, which you need to again escape in Java strings.

So use replaceAll("\\*", "A")

答案2

得分: 0

在“*1”定界符前附加“\”。

String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";
System.out.println(result.replaceAll("\\*1", "A"));
英文:

Attach \\ in front of "*1" delimeter.

String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";
System.out.println(result.replaceAll("\\*1", "A"));

答案3

得分: 0

我连接了 *1 以匹配 *1,然后将其替换为 A

class StackOverflow 
{
  public static void main(String[] args)
  {
    String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";
    String find = "*" + "1";
    result = result.replace(find, "A");
    System.out.println(result);
  }
}
//输出:
//106A51A54A45*40A45A56A43A57A44A45A62*41
英文:

I concatenated * and 1 to match *1 and replaced it with A.

class StackOverflow 
{
  public static void main(String[] args)
  {
    String result = "106*151*154*145*40*145*156*143*157*144*145*162*41";
    String find = "*" + "1";
    result = result.replace(find, "A");
    System.out.println(result);
  }
}
//Output:
//106A51A54A45*40A45A56A43A57A44A45A62*41

huangapple
  • 本文由 发表于 2020年10月2日 11:26:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64165826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定