Java 获取特定单词,后面跟单词,前面跟单词

Java 获取特定单词,后面跟单词,前面跟单词,java,regex,pattern-matching,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.forma

我需要得到一些单词的基础上,一些其他的话来后面和之前的话! 假设我有一个字符串:

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));
}

我想两个正则表达式会比较合适吗?一个选择后面跟否的单词:
/\w+(no | not)/g
,另一个选择后面跟否的单词:
/(no | not)\w+/g

尝试以下操作

(?<=no|not)\w+
这将匹配后面出现的单词
no
not


这两者的结合可能就是你想要的

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

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

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);

}

我使用了你原来的句子,你在这期间做了修改。

与同事一起做作业:?不清楚你在问什么。应该如何获得这个输出?
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,