您可以构建正则表达式来为您执行此操作:
// pattern1 and pattern2 are String objects
String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2);
这会将pattern1
andpattern2
视为文字文本,并且模式之间的文本将在第一个捕获组中捕获。Pattern.quote()
如果您想使用正则表达式,您可以删除,但如果您这样做,我不保证任何事情。
您可以通过向regexString
.
然后编译正则表达式,获取一个Matcher
对象,遍历匹配并将它们保存到 a List
(或 any 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