Java 正则表达式匹配特定单词并忽略特定文本

Java 正则表达式匹配特定单词并忽略特定文本,java,regex,groovy,Java,Regex,Groovy,我有以下错误消息列表 def errorMessages = ["Line : 1 Invoice does not foot Reported" "Line : 2 Could not parse INVOICE_DATE value" "Line 3 : Could not parse ADJUSTMENT_AMOUNT value" "Line 4 : MATH E

我有以下错误消息列表

def errorMessages = ["Line : 1 Invoice does not foot Reported"
                     "Line : 2 Could not parse INVOICE_DATE value"
                     "Line 3 : Could not parse ADJUSTMENT_AMOUNT value"
                     "Line 4 : MATH ERROR"
                     "cl_id is a required field"
                     "File Error : The file does not contain delimiters"
                     "lf_name is a required field"]
我正在尝试创建一个与
正则表达式“^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?+”
不匹配的新列表,但其文本为
发票未报告

我想要的新列表如下所示

def headErrors= ["Line : 1 Invoice does not foot Reported"
                 "cl_id is a required field"
                 "File Error : The file does not contain delimiters"
                 "lf_name is a required field"]
这就是我现在要做的

regex = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+"
errorMessages.each{
    if(it.contains('Invoice does not foot Reported'))
        headErrors.add(it)
    else if(!it.matches(regex)
        headErrors.add(it)
}
有没有一种方法可以只用regex而不是if-else来实现呢

  • 首先,匹配消息部分中包含文本
    Invoice not foot Reported
    的行

  • 然后在开始时使用否定的前瞻断言,以不匹配一行,如果该行是以实际由
    line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)
    模式匹配的字符开始的

  • 正则表达式:

    "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.*?Invoice does not foot Reported.*|^(?!Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.*).+"
    

    regex101.com上手动测试时,它看起来不错
    ,但当我在代码编译器中使用它时,会在美元符号后给出以下错误
    非法字符串体字符;解决方案:要么转义一个字面美元符号“\$5”,要么用括号括起值表达式“${5}”
    删除
    $
    符号,然后重试。谢谢您的回答。我很感激。你能帮我吗