ChrisP
ChrisP

Reputation: 10116

How to match multiple characters in a regular expression?

I have the string

7,456.23%

where I would like to use a regular expression to match BOTH the comma(,) and percent(%) characters and remove them so the result is

7456.23

I can figure out how to match one character or the other, but not both.

Upvotes: 2

Views: 5819

Answers (1)

Braj
Braj

Reputation: 46841

Simply use Character Classes or Character Sets

With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters.

Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae].

System.out.println("7,456.23%".replaceAll("[,%]",""));

OR try with ORing (Alternation Operator)

System.out.println("7,456.23%".replaceAll(",|%",""));

Upvotes: 2

Related Questions