我正在尝试解决正则表达式问题,但没有得到解决方案。
String sample1 = "Hello234Water";
String sample2 = "Hello254World";
String pat1 = "Hello(\\d+)World";
String pat2 = "Hello(\\d+)Water";
String pat = "(Hello(\\d+)World|Hello(\\d+)Water)";
Pattern p = Pattern.compile(pat, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(sample1);
if (m.find()) {
String int1 = m.group(1);
System.out.print(int1);
}
预期的响应234
但得到Hello234Water
编辑1:
我正在尝试解决正则表达式问题,但没有得到解决方案。
String sample1 = "Hot234Water";
String sample2 = "Hello254World";
String pat1 = "Hello(\\d+)World";
String pat2 = "Hot(\\d+)Water";
String pat = "(Hello(\\d+)World|Hot(\\d+)Water)";
Pattern p = Pattern.compile(pat, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(sample1);
if (m.find()) {
String int1 = m.group(1);
System.out.print(int1);
}
预期响应 234 ,但获得 Hot234Water
答案 0 :(得分:4)
您有不必要的组,也需要在正确的位置使用替换:
String pat = "Hello(\\d+)(?:World|Water)";
Pattern p = Pattern.compile(pat, Pattern.CASE_INSENSITIVE);
此外,您不需要DOTALL
模式,因为您不需要使用.
(DOT)来匹配换行符。
fyi (?:...)
被称为非捕获组。
对于您的已编辑的问题,您可以使用此正则表达式:
final String pat = "^(?=Hello\\d+World$|Hot\\d+Water$)\\D+(\\d+)";
答案 1 :(得分:0)
您可以使用this之类的工具查看您应该访问的组。非常方便!
在这种情况下,您总共有4个组:
我的建议是像其他人建议的那样简化正则表达式。