2

I am trying to execute the following operation on a 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

3
  • 3
    Use backslashes to escape. Commented Jun 27, 2013 at 20:03
  • 1
    Don't escape asterisks in contains() Commented Jun 27, 2013 at 20:06
  • Also, you need to re-assign the result of replaceAll() back to the string. Strings are immutable, and doesn't undergo in-place replacement. Commented Jun 27, 2013 at 20:08

4 Answers 4

7

replaceAll() (counter-intuitively) takes a regex, not a string.
To escape a character for a regex, you need a double-backslash (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.

Sign up to request clarification or add additional context in comments.

Comments

5

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. If you're looking for *name* in the string, you only need call combatLog.contains("*name*").

Comments

4

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.

Comments

3

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.

You have 3 options:

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.