[英]Why does this Java String.replaceAll() code not work?
I have used string.replaceAll() in Java before with no trouble, but I am stumped on this one. 我之前在Java中使用过string.replaceAll()并没有遇到任何麻烦,但我对此感到难过。 I thought it would simply just work since there are no "/" or "$" characters.
我认为它只是工作,因为没有“/”或“$”字符。 Here is what I am trying to do:
这是我想要做的:
String testString = "__constant float* windowArray";
String result = testString.replaceAll("__constant float* windowArray", "__global float* windowArray");
The variable result ends up looking the same as testString. 变量结果看起来与testString相同。 I don't understand why there is no change, please help.
我不明白为什么没有变化,请帮忙。
The first argument passed to replaceAll is still treated as a regular expression. 传递给replaceAll的第一个参数仍被视为正则表达式。 The
*
character is a special character meaning, roughly, the previous thing in the string (here: t
), can be there 0 or more times. *
字符是一个特殊字符,大致意思是字符串中的前一个字符(此处为: t
)可以有0次或更多次。 What you want to do is escape the *
for the regular expression. 你想要做的是逃避正则表达式的
*
。 Your first argument should look more like: 你的第一个论点看起来应该更像:
"__constant float\\* windowArray"
The second argument is, at least for your purposes, still just a normal string, so you don't need to escape the *
there. 第二个参数是,至少为了你的目的,仍然只是一个普通的字符串,所以你不需要在那里转义
*
。
String result = testString.replaceAll("__constant float\\* windowArray", "__global float* windowArray");
You will need to escape the * since it is a special character in regular expressions. 您将需要转义*,因为它是正则表达式中的特殊字符。
So testString.replaceAll("__constant float\\\\* windowArray", "__global float\\\\* windowArray");
所以
testString.replaceAll("__constant float\\\\* windowArray", "__global float\\\\* windowArray");
The * is a regex quantifier. *是正则表达式量词。 The replaceAll method use regex.
replaceAll方法使用正则表达式。 To avoid using regular expressions try using the replace method instead.
要避免使用正则表达式,请尝试使用replace方法。
Example: 例:
String testString = "__constant float* windowArray";
String replaceString = "__global float* windowArray";
String result = testString.replace(testString.subSequence(0, testString.length()-1),
replaceString.subSequence(0, replaceString.length()-1));
String result = testString.replaceAll("__constant float windowArray\\\\*", "__global float\\* windowArray");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.