Check if String has '+' character

Asked

Viewed 341 times

4

I need to search in a string if it has the + character, like this:

teste = teste.replaceAll("+", "e");

but I return this error:

java.util.regex.Patternssyntaxexception: Dangling meta Character '+'

  • 2

    Tries to escape the character by placing a backslash in front: \+

  • It didn’t work with + but with + thanks!!

  • 1

    @Felipekrause , in the case of Java, the escape character needs to be escaped to take effect on replace. Hence the two bars. The "compiled" result of your string (say so) is \+, as @Andersoncarloswoss said

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

1 answer

5

The character + is reserved in regular expressions, so it is necessary to escape it, however in the Java the character \ is used to escape expressions within the String, then there is the need to use it twice to ensure literal use. Substituting in your expression would look like this:

teste = teste.replaceAll("\\+", "e");

The + after a string means "one or more occurrences", for example: [0-9]+ meaning "one or more occurrences of a number (from zero to nine).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.