Luxy
Luxy

Reputation: 69

Regex not working for replacing special characters

I want to replace special characters with nothing. So i tried

this.name.replace("[^a-zA-Z]+", "").trim()

I wnat the below word to be 000 Vektor

OOO "Vektor"

Upvotes: 0

Views: 233

Answers (2)

Reimeus
Reimeus

Reputation: 159784

String.replace takes a literal first argument. replaceAll uses a regex

name = name.replaceAll("[^a-zA-Z ]+", "");

Upvotes: 1

dryairship
dryairship

Reputation: 6077

The documentation of replace says:

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

It won't take regular expressions.

The documentation of replaceAll says:

Replaces each substring of this string that matches the given regular expression with the given replacement.

So you may use:

this.name.replaceAll("[^a-zA-Z]+", "").trim();

You may also use replaceFirst with regular expressions, though not here.


Also, in a comment you say that you have tried it. I suspect that it is because you just use :

this.name.replaceAll("[^a-zA-Z]+", "").trim();

But java Strings are immutable, and don't change by themselves. Hence you should use:

this.name = this.name.replaceAll("[^a-zA-Z]+", "").trim();

Upvotes: 4

Related Questions