我正在尝试使用正则表达式在两个相同的字符串之间获取字符串。 使用该方法给出相同的字符串。
示例:相同的字符串为"blue"
"rainbowblueisskyblueisforeverblue"
会返回"isskyblueisforever"
正则表达式字符串应该匹配上面的字符串,但我有编译错误...
方法是......
public static String getSandwich(String str, String idenStr) {
Matcher m = Pattern.compile("^.*" + idenStr + "(.*?)" + idenStr + ".*$").matcher(str);
return m.group(1).toString();
}
具体来说,我收到java.lang.IllegalStateException: No match found
错误
这是逻辑错误还是风格错误?
答案 0 :(得分:1)
您需要调用Matcher.matches()
以匹配模式的输入序列。
还可以使用?
使用不情愿的表达式来匹配字符串的第一部分,以便在捕获的组中匹配isskyblueisforever
而不是isforever
。目前第一个.*
是贪婪并尽可能多地消费,包括你想要捕获的字符串:
Matcher m = Pattern.compile("^.*?" + idenStr + "(.*)" + idenStr + ".*$").matcher(str);
if (m.matches()) {
return m.group(1);
} else {
return "No match";
}
答案 1 :(得分:1)
在返回群组之前,只需检查是否存在匹配
public static String getSandwich(String str, String idenStr) {
Matcher m = Pattern.compile("^.*" + idenStr + "(.*)" + idenStr + ".*$")
.matcher(str);
if (m.matches()) {
return m.group(1).toString();
} else {
return "No match";
}
}
答案 2 :(得分:0)
请使用此
String s ="rainbowblueisskyblueisforeverblue";
System.out.println(s.substring(s.indexOf("blue")+"blue".length(),s.lastIndexOf("blue")));