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

时间:2019-07-05 04:29:54

标签: java

在给定的字符串中,我只想提取“ 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:";

2 个答案:

答案 0 :(得分:2)

有点逃避,你应该很好:

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:"

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

答案 1 :(得分:0)

我认为,这个捕捉了您想要的东西。它不是Java语言,而是纯正则表达式。

=COUNTA(UNIQUE(A1:A10))<>COUNTA(A1:A10)

这是Java示例

  var now = new Date(); // Fri Jul 05 09:53:12 GMT+05:30 2019

  var nowInMS = now.getTime(); // 1562300592245

  var add = 12 * 60 * 60 * 1000; // 43200000 = 12 hours in milliseconds

  var twelveHoursLater = nowInMS + add; // 1562343792245

  var futureDate = new Date(twelveHoursLater); // Fri Jul 05 21:53:12 GMT+05:30 2019

  var futureDateFormatted = Utilities.formatDate(futureDate, Session.getScriptTimeZone(), "dd-MMM-yy hh:mm a"); // 05-Jul-19 09:53 PM

输出:

ENERGY:\s(.*)