Is there a way to remove everything but characters, numbers and '-' from a string

I'm really bad with regex but here is what I'm trying to achieve

StringOne = [5, -, e, 4, e, e, 0, 5, 3, 5, e, b, e, e, 5, 0, a, 4, 3, 3, 1, 9, 0, 8, 1, b, 3, 6, 1, b, 3, 6, 4, d, 3, 3, -, 2, 0, c, c, 1, c, 1, -, ., 8, 3, -, 4, 8, 4, 3];

      

And I want to remove everything except numbers, symbols and '-'

I found an answer to keep characters and number by doing this

StringOne = StringOne.replaceAll("[^a-zA-Z0-9]", "");

      

But I also want to keep the '-'

Is there a way to add this to regex or regex that will remove '[' ',' ']'

+3


source to share


3 answers


Of course, add additional symbols (ie "-") to preserve the symbol class of things to be kept that has already been created and used.

At the end of a character class, "-" means itself (although it can also be escaped). So the match pattern will look like this:



"[^a-zA-Z0-9-]"

      

(This says match is to remove - anything that is not an English letter, decimal digit, or dash.)

+10


source


I actually found a way

StringOne= StrignOne.replaceAll("\\[|\\]|\\,", "");

      



Thanks to everyone who tried.

0


source


You may try

stringOne.replaceAll("^[a-zA-Z0-9-]",""):

      

Use this site to play around with regex and see if your expression is correct:

http://www.regexplanet.com/advanced/java/index.html

Edit: ^ [a-zA-Z0-9 [-]] is wrong because two sets are not included. They must be represented as one character set: [a-zA-Z0-9 -]

0


source







All Articles