gpt4 book ai didi

java - 如何为以下字符串编写正则表达式?

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

在给定的字符串中,我只想提取“ENERGY:”之后的字符串

1562173405047|INFO|MyHalfDuplexModem@30:println|ENERGY: -s 1 -d 2 -b 288 -e 9.999788799994675071125   T   {-s 1, -d 2 }
1562173405552|INFO|MyHalfDuplexModem@43:println|ENERGY: -s 3 -d 2 -b 96 -e 9.999779196127731100294 R {-s 3, -d 2 }
1562173406122|INFO|MyHalfDuplexModem@43:println|ENERGY: -s 1 -d 2 -b 288 -e 9.999764796127731100294 R {-s 1, -d 2 }
1562173406194|INFO|MyHalfDuplexModem@43:println|ENERGY: -s 2 -d 1 -b 96 -e 9.999759995924876667052 T {-s 2, -d 1 }

这是我的代码:

public static void main(String[] args) {
//movies = new ArrayList<movie>();
realPath = "Z:\\UNET\\3 NODE 1 SOURCE\\log-0.txt";
File f = new File(realPath);
if ( !f.exists()) {
System.err.println("file path not specified");
}
try {
String regex1 = "[0-9]+\|INFO\|MyHalfDuplexModem@[0-9]+:println\|ENERGY:";

Scanner sc = new Scanner(f);

while (sc.hasNextLine()) {

String nextLine = sc.nextLine();
if ( !nextLine.matches(regex1)) {
System.out.println(nextLine);
}


}

// sc.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}

我尝试了以下正则表达式,但它不起作用: regex1 = "[0-9]+[|]INFO[|]MyHalfDuplexModem@[0-9]+:println|ENERGY:";

最佳答案

稍微逃避一下,你应该会很好:

regex1 = "[0-9]+\|INFO\|MyHalfDuplexModem@[0-9]+:println\|ENERGY:";
^^ this was the problem
|
`- this is the fix

没有转义|alternation ,有效地产生 "[0-9]+|INFO|MyHalfDuplexModem@[0-9]+:println"OR "ENERGY:"

另请注意,\|[|] 相同。我更喜欢前者。

关于java - 如何为以下字符串编写正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56896573/

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