我尝试了很多,但无法找到准确的正则表达式。
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");
我想提取字符串,以this开头,以small结尾的字符串 并且不应包含 cat 之间的任何位置,使用此正则表达式无法获得所需的输出。
我想要的输出是:
this mouse is small
this toy is small
this is dog and it's small
最佳答案
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).
:它将匹配任何字符直到换行符
关于java - 为以特定字符串开始和结束的查找语句创建正则表达式,特定字符串除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235772/