为什么这个 Java String.replaceAll() 代码不起作用?
我以前在 Java 中使用过 string.replaceAll() ,没有遇到任何问题,但我对这个感到困惑。我认为它会正常工作,因为没有“/”或“$”字符。这就是我想要做的:
String testString = "__constant float* windowArray";
String result = testString.replaceAll("__constant float* windowArray", "__global float* windowArray");
变量结果最终看起来与 testString 相同。我不明白为什么没有变化,请帮忙。
I have used string.replaceAll() in Java before with no trouble, but I am stumped on this one. 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. I don't understand why there is no change, please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
传递给replaceAll 的第一个参数仍被视为正则表达式。
*
字符是一个特殊字符,大致意思是字符串中的前一个字符(此处:t
)可以出现 0 次或多次。您想要做的是转义正则表达式的*
。您的第一个参数应该看起来更像是:第二个参数至少就您的目的而言仍然只是一个普通字符串,因此您不需要在那里转义
*
。The first argument passed to replaceAll is still treated as a regular expression. The
*
character is a special character meaning, roughly, the previous thing in the string (here:t
), can be there 0 or more times. What you want to do is escape the*
for the regular expression. Your first argument should look more like:The second argument is, at least for your purposes, still just a normal string, so you don't need to escape the
*
there.您需要转义 *,因为它是正则表达式中的特殊字符。
所以
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");
* 是一个正则表达式量词。 replaceAll 方法使用正则表达式。要避免使用正则表达式,请尝试使用 replace 方法。
例子:
The * is a regex quantifier. The replaceAll method use regex. To avoid using regular expressions try using the replace method instead.
Example: