我有以下字符串,其中包含单词and
或单词or
之间的单词。
Apple and Mango or Banana or Lichi and Potato or blackberry
请指导我如何创建正则表达式,以便在字词之间匹配包含and
或or
一个或多个字词的字符串。
答案 0 :(得分:2)
\w+( (and|or) \w+)*
应该做的伎俩
答案 1 :(得分:0)
您可以通过以下方式实现此目的:
System.out.println(Arrays.toString("Apple and Mango or Banana or Lichi and Potato or blackberry".split("and|or")));
<强>输出强>
[Apple,Mango,Banana,Lichi,Potato,blackberry]
希望这有帮助。
答案 2 :(得分:0)
String s = "Apple and Mango or Banana or Lichi and Potato or blackberry";
String fruit = "(Apple|Banana|blackberry|Lichi|Mango|Potato)";
Pattern pattern = Pattern.compile("(" + fruit + " (and|or) )+" + fruit);
Matcher m = pattern.matcher(s);
if (m.matches()) {
System.out.println("Matches");
int n = m.groupCount();
for (int i = 1; i <= n; ++i) {
System.out.printf("[%d] %s%n", i, m.group(i));
}
} else {
System.out.println("No match");
}
Matches
[1] Potato or
[2] Potato
[3] or
[4] blackberry
有关信息和解释,请参阅javadoc。