Basavaraj
Basavaraj

Reputation: 1111

Regular Expression In Java Replace character and dot

Trying write regexp in java to replace character and dot with "",my string is

String value = "a.employee";

in string i want to replace a. or b. or c. with "" using ReplaceAll method in java as tried below regexp--

[a\.|b\.|c.]

but this is giving output as -

""""employee 

but it should be like

""employee

can any one give me hint to solve this.

Upvotes: 1

Views: 572

Answers (1)

rock321987
rock321987

Reputation: 11032

In character class everything is treated as single character. So in you regex

[a\.|b\.|c.]

It means match aor . or | or bor . or | or cor .. Final character class can be understood as intersection of all these characters. So in your character class, you finally have

[abc.|]

NOTE :- There is no need to escape . in character class. Inside character class | is literal pipe symbol and not the alternation that you are thinking.

Now, when you are using replaceAll on your string, it replaces your a with "" and also . with "". Thus you are getting 4 double quotes.

You can use

System.out.println("a.employee".replaceAll("[abc][.]", "\"\""));

Ideone Demo

Upvotes: 1

Related Questions