3

I am really bad with regex but here is what i am trying to acheive

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 but numbers, characters and '-'

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

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

But I also want to save '-'

Is there some way I can add that to the regex or a regex that would remove '[' ',' ']'

Frank Boyne
  • 4,400
  • 23
  • 30
Nick Div
  • 5,338
  • 12
  • 65
  • 127

3 Answers3

10

Sure, add the additional characters (ie. "-") to keep to the character class of things to keep, which is already created and used.

At the end of the character class the "-" means itself (although it could also be escaped). Thus the matching pattern becomes:

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

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

user2864740
  • 60,010
  • 15
  • 145
  • 220
1

You could 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[-]] was incorrect because the two sets are not inclusive. They should be represented as one set of characters: [a-zA-Z0-9-]

Yon Kornilov
  • 101
  • 4
0

I actually found a way

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

Thanks for anyone who was trying.

Nick Div
  • 5,338
  • 12
  • 65
  • 127