简体   繁体   English

在java中转义*字符

[英]Escaping * character in java

I am trying to execute the following operation on a String. 我试图在String上执行以下操作。

    if (combatLog.contains("//*name//*")) {
        combatLog.replaceAll("//*name//*",glad.target.name);
    }

The slashes are my attempt to escape the *, as it doesn't work without them. 斜杠是我试图逃避*,因为没有它们就行不通。 I have also tried one slash, and slashes on contains or replaceAll individually. 我还尝试了一个斜杠,并且单独包含或替换所有斜杠。 Thanks 谢谢

replaceAll() (counter-intuitively) takes a regex, not a string. replaceAll() (反直觉地)采用正则表达式,而不是字符串。
To escape a character for a regex, you need a double- back slash (doubled to escape the backslash from the string literal). 要转义正则表达式的字符,你需要一个双斜杠(加倍来逃避字符串文字的反斜杠)。

However, you don't want a regex. 但是,您不需要正则表达式。 You should simply call replace() instead, which won't need any escaping. 你应该简单地调用replace() ,这不需要任何转义。

You're using forward slashes. 你正在使用正斜杠。 The backslash is the escape character. 反斜杠是转义字符。 Furthermore, unless the string is being used for regex or something similar, you need not escape the * , or the / if thats what you're trying to escape. 此外,除非字符串用于正则表达式或类似的东西,否则你不需要逃避* ,或者/那就是你想要逃脱的东西。

If combatLog is a String, its contains method checks for a sequence of characters only. 如果combatLog是String,则其contains方法仅检查字符序列。 If you're looking for *name* in the string, you only need call combatLog.contains("*name*") . 如果您在字符串中查找*name* ,则只需要调用combatLog.contains("*name*")

You are using forward slashes use the backslash: \\ to escape characters 您正在使用正斜杠使用反斜杠: \\来转义字符

[edit] also as slaks said you need to use replace() which accepts a string as input rather than a regex. [编辑]也像slaks说你需要使用replace()接受字符串作为输入而不是正则表达式。

Don't forget about immutability of strings, and reassign the newly created string. 不要忘记字符串的不变性 ,并重新分配新创建的字符串。 Also, if your if block doesn't contain any more code, you don't need the if check at all. 此外,如果您的if块不包含任何其他代码,则根本不需要if检查。

You have 3 options: 你有3个选择:

if (combatLog.contains("*name*")) { // don't escape in contains()
    combatLog = combatLog.replaceAll("\\*name\\*", replacement);// correct escape
}
// another regex based solution
if (combatLog.contains("*name*")) {
    combatLog = combatLog.replaceAll("[*]name[*]", replacement);// character class
}

or without a regex 或没有正则表达式

if (combatLog.contains("*name*")) {
    combatLog = combatLog.replace("*name*", replacement);// literal string
}

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

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