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

标签 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");

我想提取字符串,以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) :如果前面没有猫则匹配

.*? :匹配任何字符,尽可能少的次数

RegexDemo


更新:

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/

相关文章:

javascript - 用一个正则表达式解析复杂的字符串

regex - 如何在 ABAP 中使用 RegEx 查找任何非数字字符

mysql - 如何使下面的正则表达式适用于 MySql?

java - 关于 setActionCommand 方法

java - quartz 我如何将 JobExecutionContext 和 Scheduler 的范围更改为类级别?

java - 如何在 Java 中使用进度条(Netbeans GUI)

c# - 允许以大写字母开头,后跟小写字母的正则表达式是什么?

java - 数据库负载均衡

java - 如何使用 javafx 在 Gluon 移动应用程序中切换 View ?

java - Java 验证中的正则表达式帮助