如何将字符串与单词匹配'和'或者'或'这两个词之间?

时间:2014-07-15 07:48:50

标签: java regex

我有以下字符串,其中包含单词and或单词or之间的单词。

Apple and Mango or Banana or Lichi and Potato or blackberry

请指导我如何创建正则表达式,以便在字词之间匹配包含andor一个或多个字词的字符串。

3 个答案:

答案 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