我尝试了很多但无法找到确切的正则表达式。
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
答案 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)
:匹配,如果没有猫在前面
.*?
:尽可能少地匹配任何字符
更新:
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$");