您可以构造正则表达式来为您执行此操作:
// pattern1 and pattern2 are String objects
String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2);
这会将 和 视为文字文本,并且模式之间的文本将在第一个捕获组中捕获。如果你想使用正则表达式,你可以删除Pattern.quote(),
但如果你这样做,我不能保证任何事情。pattern1
pattern2
您可以通过向 添加标志来添加一些匹配方式的自定义。regexString
然后编译正则表达式,获取 Matcher
对象,循环访问匹配项并将其保存到(或任何 ,由您决定)List
Collection
Pattern pattern = Pattern.compile(regexString);
// text contains the full text that you want to extract data
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String textInBetween = matcher.group(1); // Since (.*?) is capturing group 1
// You can insert match into a List/Collection here
}
测试代码:
String pattern1 = "hgb";
String pattern2 = "|";
String text = "sdfjsdkhfkjsdf hgb sdjfkhsdkfsdf |sdfjksdhfjksd sdf sdkjfhsdkf | sdkjfh hgb sdkjfdshfks|";
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group(1));
}
请注意,如果您使用上述方法在此输入之间和其中搜索文本,您将获得一个匹配项,即 .foo
bar
foo text foo text bar text bar
text foo text