获取特定单词后跟单词并以单词开头

时间:2016-01-10 13:45:38

标签: java regex pattern-matching

我需要根据言语之前和之前的其他一些词语得到一些词语! 假设我有一个字符串:

not me and you but me and no you but me not

这样输出应为:

not me
and no
no you
me not

简单来说,我希望得到没有的词,而不是在特定词之后或之前得到的词! 我正在尝试:

String regex = "(?i)%s\\s+([\\S]+)\\s+([\\S]+)";
Matcher m = Pattern.compile(String.format(regex, Pattern.quote("no"))).matcher("not me and you but me and no you but me not");

while (m.find())
{
    System.out.println(m.group(1));
}

3 个答案:

答案 0 :(得分:0)

我认为两个正则表达式适合吗?一个选择任何单词,然后选择否:/\w+( no| not)/g和一个用于选择否或不选择任何单词:/(no |not )\w+/g

答案 1 :(得分:0)

尝试以下

(?<=no|not)\w+

这将匹配nonot

之后的字词
\w+(?=no|not)

这将匹配nonot之后的字词。

现在结合这两个可能是你想要的。

(?<=no|not)\w+(?=no|not)

答案 2 :(得分:0)

更复杂的解决方案可能看起来像

public  void  getWords(){
    String str = "I have not used no  water but the water not used by me and no sea not but water no!";
    String[] words = str.split(" +|\t+|!");//split by space, tab and exclamation mark

    int currentPos = 0;
    int len = words.length;
    List<String> matchedWords = new ArrayList<String>();
    for(int i=0;i<len;i++){
        if("no".equals(words[i])||"not".equals(words[i])){
            if(currentPos!=i-1&&i-1>=0)//so we leave out duplicate words
                matchedWords.add(words[i-1]);
            if(i+1<len-1)
                matchedWords.add(words[i+1]);//
            currentPos = i+1;
        }
    }

    for(String s : matchedWords)
        System.out.println(s);

}

输出

 have, used, water, water, used, and, sea, but, water, 

我使用了你原来的句子,你在此期间已经改变了。

相关问题