Match regex from right to left?

后端 未结 6 452
心在旅途
心在旅途 2020-12-11 15:27

Is there any way of matching a regex from right to left? What Im looking for is a regex that gets

MODULE WAS INSERTED              EVENT
LOST SIGNAL ON E1/T         


        
6条回答
  •  一个人的身影
    2020-12-11 15:50

    Does the input file fit nicely into fixed width tabular text like this? Because if it does, then the simplest solution is to just take the right substring of each line, from column 56 to column 94.

    In Unix, you can use the cut command:

    cut -c56-94 yourfile
    

    See also

    • Wikipedia/Cut (Unix)

    In Java, you can write something like this:

    String[] lines = {
        "CLI MUX trap received: (022) CL-B  MCL-2ETH             MODULE WAS INSERTED              EVENT   07-05-2010 12:08:40",
        "CLI MUX trap received: (090) IO-2  ML-1E1        EX1    LOST SIGNAL ON E1/T1 LINK        OFF     04-06-2010 09:58:58",
        "CLI MUX trap received: (094) IO-2  ML-1E1        EX1    CRC ERROR                        EVENT   04-06-2010 09:58:59",
        "CLI MUX trap received: (009)                            CLK IS DIFF FROM MASTER CLK SRC  OFF     07-05-2010 12:07:32",
    };
    for (String line : lines) {
        System.out.println(line.substring(56, 94));
    }
    

    This prints:

    MODULE WAS INSERTED              EVENT
    LOST SIGNAL ON E1/T1 LINK        OFF  
    CRC ERROR                        EVENT
    CLK IS DIFF FROM MASTER CLK SRC  OFF  
    

    A regex solution

    This is most likely not necessary, but something like this works (as seen on ideone.com):

    line.replaceAll(".*  \\b(.+  .+)   \\S+ \\S+", "$1")
    

    As you can see, it's not very readable, and you have to know your regex to really understand what's going on.

    Essentially you match this to each line:

    .*  \b(.+  .+)   \S+ \S+
    

    And you replace it with whatever group 1 matched. This relies on the usage of two consecutive spaces exclusively for separating the columns in this table.

提交回复
热议问题