为什么此 Java String.replaceAll() 代码不起作用? [英] Why does this Java String.replaceAll() code not work?
问题描述
我之前在 Java 中使用过 string.replaceAll() 并没有遇到任何问题,但我对这个感到困惑.我认为它只会起作用,因为没有/"或$"字符.这是我想要做的:
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");
变量结果最终看起来与 testString 相同.我不明白为什么没有变化,请帮忙.
The variable result ends up looking the same as testString. I don't understand why there is no change, please help.
推荐答案
传递给 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:
"__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");
这篇关于为什么此 Java String.replaceAll() 代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!