为什么p {Digit}模式在Java中不起作用?

时间:2019-07-31 22:38:38

标签: java regex

我正在使用p {Digit}来验证字符串。但是,当我使用“101ᶁ1”时,结果为true。这发生在某些符号上:ᶁ,ﻹ

Pattern p = Pattern.compile("[\\p{Digit}]");
boolean result = p.matcher(value).find();

我在文档中找不到经过验证的字符。

2 个答案:

答案 0 :(得分:1)

我相信您误解了find()的用法。它在搜索到的文本中搜索正则表达式的第一个匹配项 any ({Pattern.start()返回找到表达式的位置)

表达式"[\\p{Digit}]"-[]在这里什么也不做-只是匹配一位数字。由于搜索的文本具有数字,因此find()的结果为true

要匹配整个文本,表达式必须以^开头以匹配文本的开头,并以与文本结尾相对应的$结束。而且它必须允许一个以上的数字,因此它需要一个+(一个或多个),导致

Pattern p = Pattern.compile("^\\p{Digit}+$");
boolean result = p.matcher(value).find();

matches()可用于对整个文本进行测试,因此不需要^$-仍需要+才能允许多于一个数字:< / p>

Pattern p = Pattern.compile("\\p{Digit}+");
boolean result = p.matcher(value).matches();

注意:这可以写成:

boolean result = value.matches("\\p{Digit}+");

答案 1 :(得分:0)

POSIX字符类仅是US-ASCII。

如您所见:

String value = "101ᶁ1";
Pattern p = Pattern.compile("[\\p{Digit}]");
Matcher m = p.matcher(value);
while (m.find())
    System.out.println(m.group());

输出为:

1
0
1
1

您的角色被跳过。对于您的用例,您应该编写自己的isDigit方法。

有几种方法可以做到:

// option 1: regex
String regex = "[0-9]+";
// or
String regex = "\\d+";

// option 2: parse and exception
try {
    long n = Long.parseLong(data)
} catch (NumberFormatException nfe) {
    // do something
}

// option 3: Java-8 streams
boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));

希望这会有所帮助。祝你好运。

第一个代码阻止者为:https://stackoverflow.com/users/1553851/shmosel