[英]Regex for numeric portion of Java string
我正在尝试编写一个Java方法,该方法将字符串作为参数,并在匹配模式时返回另一个字符串,否则返回null
。 模式:
:
”); 然后是 因此,一些与该模式匹配的有效字符串:
50: hello
1: d
10938484: 394958558
还有一些与该模式不匹配的字符串:
korfed49
: e4949
6
6:
6:sdjjd4
该方法的一般框架是这样的:
public String extractNumber(String toMatch) {
// If toMatch matches the pattern, extract the first number
// (everything prior to the colon).
// Else, return null.
}
到目前为止,这是我最好的尝试,但是我知道我错了:
public String extractNumber(String toMatch) {
// If toMatch matches the pattern, extract the first number
// (everything prior to the colon).
String regex = "???";
if(toMatch.matches(regex))
return toMatch.substring(0, toMatch.indexOf(":"));
// Else, return null.
return null;
}
提前致谢。
您的描述很详细,现在只需将其翻译为正则表达式即可:
^ # Starts
\d+ # with a number (1+ digits); then followed by
: # A colon (":"); then followed by
# A single whitespace (" "); then followed by
\w+ # Any word character, one one more times
$ # (followed by the end of input)
用Java字符串给出:
"^\\d+: \\w+$"
您还想捕获数字:在\\d+
加上括号,使用Matcher
,并在存在匹配项的情况下捕获组1:
private static final Pattern PATTERN = Pattern.compile("^(\\d+): \\w+$");
// ...
public String extractNumber(String toMatch) {
Matcher m = PATTERN.matcher(toMatch);
return m.find() ? m.group(1) : null;
}
注意:在Java中, \\w
仅匹配ASCII字符和数字(例如,.NET语言不是这种情况),并且还将匹配下划线。 如果您不想使用下划线,则可以使用(特定于Java的语法):
[\w&&[^_]]
而不是\\w
作为正则表达式的最后一部分,给出:
"^(\\d+): [\\w&&[^_]]+$"
尝试使用以下命令:\\ d +:\\ w +
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.