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

你说的曾经没有我的故事 提交于 2021-01-27 16:43:48

问题


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 '[' ',' ']'


回答1:


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.)




回答2:


I actually found a way

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

Thanks for anyone who was trying.




回答3:


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-]



来源:https://stackoverflow.com/questions/31364852/is-there-a-way-to-remove-everything-except-characters-numbers-and-from-a-st

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!