3 回答

TA贡献1898条经验 获得超8个赞
您可以使用的一个可能的正则表达式是:
^((\d+\.)*\d+) \D*$
捕获组 1 将在哪里举行您的比赛。
解释:
^ # Start of the String
( # Open capture group 1:
(\d+\.) # One or more digits, followed by a dot
* # Repeated 0 or more times
\d+ # Followed by 1 or more digits
) # Closing capture group 1
# Followed by a space
\D* # Followed by 0 or more non-digits
$ # Followed by the end of the String
和^将使$我们查看整个字符串。这\D*将确保空格后的子字符串中没有任何数字。并且确保始终有一个前导数字,在它之前有一个或多个\d+(其中是非负数)。(\d+\.)*#.#
要提取此值,您可以将此正则表达式与 a 一起使用String.matches,.replaceFirst如下所示:
// TODO: Give proper method name
String test(String str){
String regex = "^((\\d+\\.)*\\d+) \\D*$";
if(str.matches(regex))
return str.replaceFirst(regex, "$1");
// The `$1` will leave just the match of the first capture group,
// removing everything else we don't need
else
return null;
}
如果后面没有任何空格的单个数字(即"123"
)也应该匹配,则可以通过更改为对正则表达式进行细微修改\\D*$
,( \\D*)?$
以便空格变为可选。

TA贡献1836条经验 获得超4个赞
Using(\d+\.)+\d
不会匹配第一个条目,因为使用量词+
它必须至少匹配一个数字和一个点。
您可能会做的是使用锚^
来断言字符串的开头并使用模式来匹配数字,然后重复匹配点和数字零次或多次,这样您也可以匹配第一个条目。
匹配后,确保数字后面没有非空白字符。如果后面不能有更多数字,您可以使用额外的负前瞻。
^\d+(?:\.\d+)*(?!\S)(?!.*\d)
在 Java 中:
String regex = "^\\d+(?:\\.\\d+)*(?!\\S)(?!.*\\d)";
解释
^
字符串的开始\d+(?:\.\d+)*
匹配 1+ 位数字,后跟重复模式以匹配点和 1+ 位数字(?!\S)
负前瞻检查左边的内容不是非空白字符(?!.*\d)
负前瞻检查右边的内容不包含数字

TA贡献1816条经验 获得超4个赞
我们可以尝试对每一行使用以下正则表达式模式:
^(?!\D*\d[^0-9.]+\d).*\b\d+(?:\.\d+)?(?=\\s|$).*$
解释:
^ from the start of the line
(?!\D*\d[^0-9.]+\d) assert that two (or more) separate numbers
do not occur in the line
.* then consume anything, up to
\b\d+(?:\.\d+)? an integer, or complete decimal
(?=\\s|$) where either a space or the end of the line follows
.* then consume anything, up to
$ the end of the line
这是使用此模式的 Java 代码:
String line = "45.67.21234.3";
String pattern = "^(?!\\D*\\d[^0-9.]+\\d).*\\b\\d+(?:\\.\\d+)?(?=\\s|$).*$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("match");
}
else {
System.out.println("no match");
}
我已经根据您的所有输入对其进行了测试,它似乎正在工作。
添加回答
举报