为特定字符串开始和结束的查找语句创建正则表达式,但特定字符串除外

时间:2016-12-20 05:56:33

标签: java regex

我尝试了很多但无法找到确切的正则表达式。

String str = "this cat is small. dog is pet anmial. this mouse is small.this toy is small. this is a cat and it's small. this is dog and it's small.  ";
Pattern ptr = Pattern.compile("this.*((?!(cat).)*).*small");

我想提取字符串,字符串以开头,以结尾 并且不应该包含 cat 之间的任何地方,它没有得到使用此正则表达式的欲望输出。

我的愿望输出是:

                this mouse is small
                this toy is small  
                this is dog and it's small

3 个答案:

答案 0 :(得分:4)

String str = "this cat is small. dog is pet anmial. this mouse is small.this toy is small.";
Pattern ptr = Pattern.compile("this\\s(?!cat).*?small");
Matcher matcher=ptr.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

<强>输出:

this mouse is small
this toy is small

this\\s(?!cat).*?small:以this开头,以small

结尾

(?!cat):匹配,如果没有猫在前面

.*?:尽可能少地匹配任何字符

RegexDemo

更新:

Regex demo this((?!cat).)*?small

输出:

this mouse is small
this toy is small
this is dog and it's small

(?!cat).:它会匹配任何字符直到换行

答案 1 :(得分:0)

使用此

   String str = "this cat is small. dog is pet anmial. this mouse is    small.this toy is small.";
   Pattern .compile(^this.*\bsmall);

   Pattern .compile(^this.*small$);

答案 2 :(得分:-1)

尝试使用

String input = "this mouse is small this toy is small";
boolean matches = input.matches("^This.*small$");