用于Java字符串的数字部分的正则表达式
我正在尝试编写一个Java方法,该方法将一个字符串作为参数,如果它与模式匹配,则返回另一个字符串,否则返回用于Java字符串的数字部分的正则表达式,java,regex,Java,Regex,我正在尝试编写一个Java方法,该方法将一个字符串作为参数,如果它与模式匹配,则返回另一个字符串,否则返回null。模式: 以数字(1+位数)开头;然后是 冒号(“:”);然后是 单个空格(“”);然后是 任何1个以上字符的Java字符串 因此,一些与此模式匹配的有效字符串: 50: hello 1: d 10938484: 394958558 korfed49 : e4949 6 6: 6:sdjjd4 以及一些与此模式不匹配的字符串: 50: hello 1: d 10938484:
null
。模式:
- 以数字(1+位数)开头;然后是
- 冒号(“
”);然后是:
- 单个空格(“”);然后是
- 任何1个以上字符的Java字符串
50: hello
1: d
10938484: 394958558
korfed49
: e4949
6
6:
6:sdjjd4
以及一些与此模式不匹配的字符串:
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;
}
提前感谢。尝试使用下列命令:\d+:\w+尝试使用下列命令:\d+:\w+您的描述非常准确,现在只需将其转换为正则表达式即可:
^ # 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+
周围放上括号,使用匹配器,如果存在匹配项,则捕获组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
,给出:
"^(\\d+): [\\w&&[^_]]+$"
您的描述非常准确,现在只需将其翻译为正则表达式:
^ # 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+
周围放上括号,使用匹配器,如果存在匹配项,则捕获组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
,给出:
"^(\\d+): [\\w&&[^_]]+$"
@smit是的,考虑到使用了.matches()
方法,我真的很讨厌这个方法的名称,Java犯了一个错误,我不明白你说的是什么意思。你能说得更清楚些吗?@smit:当你使用.matches()
时,就像你用^
和$
包围了整个正则表达式一样——这与正则表达式匹配的定义相矛盾,正则表达式匹配可以发生在输入的任何地方。Java中真正的正则表达式匹配是使用.find()
完成的。我明白你的意思。在阅读java文档之后,它变得更加清晰了。我认为这个链接可能有用@smit是的,考虑到使用了.matches()
方法,我真的很讨厌这个方法的名称,Java犯了一个错误,我不明白你说的是什么意思。你能说得更清楚些吗?@smit:当你使用.matches()
时,就像你用^
和$
包围了整个正则表达式一样——这与正则表达式匹配的定义相矛盾,正则表达式匹配可以发生在输入的任何地方。Java中真正的正则表达式匹配是使用.find()
完成的。我明白你的意思。在阅读java文档之后,它变得更加清晰了。我认为这个链接可能有用。