gpt4 book ai didi

java - 如何使这个正则表达式为负?

转载 作者:行者123 更新时间:2023-12-02 01:24:33 26 4
gpt4 key购买 nike

我想得到这个模式的负片

Pattern pt = Pattern.compile("FOR,FGS-(AX|AX2|AXMM|EMP|LV1|MLE)," + "(.*?)" + "FOR,");

我尝试了这个,但没有成功

Pattern pt = Pattern.compile("[^FOR,FGS-(AX|AX2|AXMM|EMP|LV1|MLE)," + "(.*?)" + "FOR,]");

我遇到了这个错误:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 10 [^FOR,FGS-(AX|AX2|AXMM|EMP|LV1|MLE),(.*?)FOR,] ^ at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.range(Unknown Source) at java.util.regex.Pattern.clazz(Unknown Source) at java.util.regex.Pattern.sequence(Unknown Source) at java.util.regex.Pattern.expr(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source)

最佳答案

我猜您可能希望设计一个表达式来排除列出的字符串,也许是一个类似于以下内容的表达式:

^(?!.*(FOR,FGS-(AX|AX2|AXMM|EMP|LV1|MLE))).*$

该表达式在 regex101.com 的右上角面板中进行了解释,如果您想探索/简化/修改它,请在this link中,如果您愿意,您可以观察它如何与一些示例输入匹配。

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^(?!.*(FOR,FGS-(AX|AX2|AXMM|EMP|LV1|MLE))).*$";
final String string = "Anything before, FOR,FGS-AX, some other things FOR, anything you wish after\n"
+ "Anything before, FOR,FGS-AX2, some other things FOR, anything you wish after \n"
+ "Anything before, FOR,FGS-EMP, some other things FOR, anything you wish after\n"
+ "Anything before, FOR,FGS-AX2, some other things FOR, anything you wish after \n"
+ "Anything before, FOR,FGS-AX2, some other things FOR, anything you wish after \n"
+ "Anything before, FOR,FGS-AXMM, some other things FOR, anything you wish after \n"
+ "Anything before, FOR,FGS-NOTAXMM, some other things FOR, anything you wish after ";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}

正则表达式电路

jex.im可视化正则表达式:

enter image description here

<小时/>

编辑

使用正则表达式执行此任务相当复杂,如果可能的话,也许您会尝试将其拆分为一个数组,然后使用简单的表达式进行检查,排除不需要的表达式,最后加入其他表达式。

如果可能的话,字符串替换也可能是另一种选择。

<小时/>

这些表达式也可以查看:

DEMO 1

DEMO 2

关于java - 如何使这个正则表达式为负?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134353/

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