我想检查我的字符串是否只包含允许的字符。一切正常,例如7B
、77B
或7BBBB
,但是当我输入这样的东西时7B7
或7BB2
它不匹配。
一切正常,但是当整数是最后一个字符时,它不起作用。
你能告诉我那个代码有什么问题吗?
pattern = Pattern.compile("[0-9]*[a-f]*[A-F]*");
matcher = pattern.matcher(stNumber);
if (matcher.matches()) {...}
如果你想
以各种顺序混合数字和字符,你需要像这样:
Pattern pattern = Pattern.compile("[\da-fA-F]*")
为什么不试试这种方式呢?
// Compile this pattern.
Pattern pattern = Pattern.compile("[0-9]*[a-f]*[A-F]*[0-9]*");
// See if this String matches.
Matcher m = pattern.matcher("num123");
if (m.matches()) {
System.out.println(true);
}
源
您是否正在尝试验证字符串是否只有数字和字母,而没有其他内容?
如果是这样,请尝试使用以下方法:
pattern = Pattern.compile("^[a-z-A-Z\d]*$");
matcher = pattern.matcher(stNumber);
if (matcher.matches()) {...}