gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:36:28 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com