Java模式匹配器未按预期用于正则表达式
上述代码的输出为:ok 但以下代码没有打印任何内容:Java模式匹配器未按预期用于正则表达式,java,regex,pattern-matching,matcher,Java,Regex,Pattern Matching,Matcher,上述代码的输出为:ok 但以下代码没有打印任何内容: 1) Pattern pattern = Pattern.compile("34238"); Matcher matcher = pattern.matcher("6003 Honore Ave Suite 101 Sarasota Florida, 34238"); if (matcher.find()) { System.out.println("ok"); } 2) Pattern pa
1) Pattern pattern = Pattern.compile("34238");
Matcher matcher = pattern.matcher("6003 Honore Ave Suite 101 Sarasota Florida,
34238");
if (matcher.find()) {
System.out.println("ok");
}
2) Pattern pattern = Pattern.compile("^[0-9]{5}(?:-[0-9]{4})?$");
Matcher matcher = pattern.matcher("34238");
if (matcher.find()) {
System.out.println("ok");
}
这不打印ok的原因是什么?我在这里也使用相同的模式。代码很好,工作正常。在问题的第2和第3部分中,您使用的是相同的正则表达式,但输入字符串不同 但是,如果您只想检查字符串是否必须包含美国邮政编码,那么问题在于您的正则表达式使用的是锚点,因此您只匹配以邮政编码开头和结尾的行 与正则表达式匹配的字符串类似于34238或34238-1234,与12345之类的字符串不匹配 如果移除锚定,则将匹配以下内容: 顺便说一句,如果您只想检查字符串是否包含邮政编码,则可以使用string.matches..,如下所示:
// Pattern pattern = Pattern.compile("^[0-9]{5}(?:-[0-9]{4})?$");
// ^--------- Here -------^
Pattern pattern = Pattern.compile("[0-9]{5}(?:-[0-9]{4})?");
Matcher matcher = pattern.matcher("6003 Honore Ave Suite 101 Sarasota Florida, 34238");
if (matcher.find()) {
System.out.println("ok");
}
虽然模式相同,但输入字符串不同: 在第二个示例中,您正在匹配一个完全由邮政编码组成的字符串,因此得到了^…$表达式的匹配项 第二个示例不是以邮政编码开头的,因此^anchor会阻止您的正则表达式匹配。
^如果希望表达式与整个输入行匹配,则使用$anchors。如果要在开头匹配,请保留“^”,然后删除$;如果要在末尾进行匹配,请删除“^”,并保留“$”;当你想匹配字符串中的任何位置时,移除两个锚。为什么不使用6003 Honore Ave Suite 101佛罗里达萨拉索塔,34238。包含34238?这是美国邮政编码格式。我们不确定是否会得到相同的结果。最后,我必须找到句子是否有美国邮政编码。这两个块中的哪一个产生ok?第一块和第二块
// Pattern pattern = Pattern.compile("^[0-9]{5}(?:-[0-9]{4})?$");
// ^--------- Here -------^
Pattern pattern = Pattern.compile("[0-9]{5}(?:-[0-9]{4})?");
Matcher matcher = pattern.matcher("6003 Honore Ave Suite 101 Sarasota Florida, 34238");
if (matcher.find()) {
System.out.println("ok");
}
String str = "6003 Honore Ave Suite 101 Sarasota Florida, 34238";
if (str.matches(".*[0-9]{5}(?:-[0-9]{4})?.*")) {
System.out.println("ok");
}