gpt4 book ai didi

java - 数据行与正则表达式模式不匹配

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:05 25 4
gpt4 key购买 nike

我正在尝试使用以下模式解析数据行:

1337;GROUP;VARIABLE;13.37;key=value;key=value;key=value ...(and so on)

它基本上是数字?;名称?;名称?;值;(key=value)*

; 分隔符可以设置为任何字符串。例如,如果设置为 FOO,则该行数据将被视为有效:

1337FOOGROUPFOOVARIABLEFOO13.37FOOkey=value

由于只有 Value 是强制性的,因此该行也将被视为有效:

FOOFOOFOO13.37

我尝试了以下测试代码:

private static final String BASE_PAYLOAD_DATA = "\\s*(\\d*SEPNOTSEP*SEPNOTSEP*SEPNOTSEP+(?:SEPNOTSEP*=NOTSEP*)*)\\s*$";

public static void main(String[] args) {
String line = "1337;GROUP;VARIABLE;13.37;key=value";
String separator = ";";

String processed = StringUtils.replace(BASE_PAYLOAD_DATA, "NOTSEP", "(?!" + separator + ")");
processed = StringUtils.replace(processed, "SEP", "(?:" + separator + ")");
System.out.println(processed);

Pattern payloadData = Pattern.compile(processed);
System.out.println(payloadData.matcher(line).matches());
}

但是测试的行不匹配。 SEPNOTSEP 字符串用于模拟可以配置分隔符的事实。

输出:

\s*(\d*(?:;)(?!;)*(?:;)(?!;)*(?:;)(?!;)+(?:(?:;)(?!;)*=(?!;)*)*)\s*$
false

我已经对模式进行了两次和三次检查,但我似乎无法指出错误的元素,而且我担心我可能会遗漏一些太明显的东西。

或者是否有关于我缺少的非记录和负面前瞻组的行为?

此外,是否有更优雅的方式来声明正则表达式模式?

谢谢!

编辑

从这个Regex Tutorial看来:

The lookahead itself is not a capturing group. It is not included in the count towards numbering the backreferences. If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)).

我会尝试一下。

最佳答案

用非捕获组包围负面前瞻组,每个组都可以量化它们,正如我在编辑中链接的那样( Regex Tutorial ):

The lookahead itself is not a capturing group. It is not included in the count towards numbering the backreferences. If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)).

我最终决定使用限制较少的正则表达式,用分隔符分割行,并使用更基于 Java 的方法分析标记(比较标记等)。

关于java - 数据行与正则表达式模式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25669037/

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