如何使用正则表达式匹配所有数字字符和某些单个字符 [英] How to match all numerical characters and some single characters using regex

查看:232
本文介绍了如何使用正则表达式匹配所有数字字符和某些单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用正则表达式匹配字符串中的所有数字和特定字符?到目前为止,我有这个

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;

我对正则表达式不太了解,但是它可以匹配0-9之间的所有字符,现在我需要能够匹配其他特定字符,例如"/",:","$"

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 "/", ":", "$"

推荐答案

您可以将其他需要匹配的字符添加到字符组的末尾,如下所示:

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;

您需要注意以下几点:

  • 如果 ^ 是字符中的字符,则不能是该组中的第一个字符
  • 如果-在字符中,则它必须是组中的最后一个字符
  • 如果] 位于字符之间,则对于regex和Java需要对其进行转义,例如 [\\]]
  • 如果 \ 位于字符之间,则对于regex和Java需要对其进行转义,例如 [\\\\]
  • 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. [\\\\]

这篇关于如何使用正则表达式匹配所有数字字符和某些单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆