我试图使用模式来搜索字符串中的邮政编码.我无法让它正常工作.
inputLine的一个示例是
What is the weather in 75042?
Run Code Online (Sandbox Code Playgroud)
我试图用于模式的是
public String getZipcode(String inputLine) {
Pattern pattern = Pattern.compile(".*weather.*([0-9]+).*");
Matcher matcher = pattern.matcher(inputLine);
if (matcher.find()) {
return matcher.group(1).toString();
}
return "Zipcode Not Found.";
}
Run Code Online (Sandbox Code Playgroud)
如果我只想获得75002,我需要更改什么?这只输出数字2中的最后一位数字.我非常困惑,我不完全理解Pattern类的Javadoc.
原因是因为.*匹配第一个数字并且只留下一个用于捕获组的数字,所以必须将其丢弃
这里可以使用更简单的模式:\D+(\d+)\D+这意味着
\D+,然后一些数字捕获 (\d+),然后一些非数字 \D+public String getZipcode(String inputLine) {
Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+");
Matcher matcher = pattern.matcher(inputLine);
if (matcher.find()) {
return matcher.group(1).toString();
}
return "Zipcode Not Found.";
}
Run Code Online (Sandbox Code Playgroud)
您的.*weather.*([0-9]+).*模式会抓取第一个的整行并.*回溯到 find weather,如果找到它,它会抓取单词后面的行部分到后续模式的行尾,.*并再次回溯以找到最后一个数字和唯一的一个数字由于一位数字满足模式,因此存储在捕获组 1 中[0-9]+。最后一个.*只会消耗该行直到其末尾。
".*weather.*?([0-9]+).*"您可以通过使用(使第二个变得懒惰)来解决问题.*,但由于您正在使用Matcher#find(),您可以使用更简单的正则表达式:
Pattern pattern = Pattern.compile("weather\\D*(\\d+)");
Run Code Online (Sandbox Code Playgroud)
获得匹配后,使用 检索值matcher.group(1)。
请参阅 正则表达式演示。
图案细节
weather- 一个weather字\\D*- 0+ 数字以外的字符(\\d+)- 捕获组 1:一位或多位数字请参阅Java 演示:
String inputLine = "What is the weather in 75042?";
Pattern pattern = Pattern.compile("weather\\D*(\\d+)");
Matcher matcher = pattern.matcher(inputLine);
if (matcher.find()) {
System.out.println(matcher.group(1)); // => 75042
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |