How to match all numerical characters and some single characters using regex

不羁的心 提交于 2021-02-05 11:32:08

问题


How can I match all numbers along with specific characters in a String using regex? I have this so far

if (!s.matches("[0-9]+")) return false;

I don't understand much regex, but this matches all characters from 0-9 and now I need to be able to match other specific characters, for example "/", ":", "$"


回答1:


You can use this regex by including those symbols in a character class:

s.matches("[0-9$/:]+")

Read more about character class




回答2:


You can add the other characters that you need to match to the end of the character group, like this:

if (!s.matches("[0-9/:$]+")) return false;

You need to be careful about several things:

  • If ^ is among the characters, it must not be the first one of the group
  • If - is among the characters, it must be the last one in the group
  • If ] is among the characters, it needs to be escaped for regex and for Java, e.g. [\\]]
  • If \ is among the characters, it needs to be escaped for regex and for Java, e.g. [\\\\]



回答3:


Regex:

String regex = "\\d/:$+";


来源:https://stackoverflow.com/questions/20952787/how-to-match-all-numerical-characters-and-some-single-characters-using-regex

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