Match regex from right to left?

后端 未结 6 450
心在旅途
心在旅途 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:51

    If tokens are guaranteed to be separated by more than one space and words within the string before EVENT|OFF are guaranteed to be separated by just one space - only then you can look for single-space-separated words followed by spaces followed by EVENT or OFF

    var s = "CLI MUX trap received: (022) CL-B  MCL-2ETH             MODULE WAS INSERTED              EVENT   07-05-2010 12:08:40"
            + "\nCLI MUX trap received: (090) IO-2  ML-1E1        EX1    LOST SIGNAL ON E1/T1 LINK        OFF     04-06-2010 09:58:58"
            + "\nCLI MUX trap received: (094) IO-2  ML-1E1        EX1    CRC ERROR                        EVENT   04-06-2010 09:58:59"
            + "\nCLI MUX trap received: (009)                            CLK IS DIFF FROM MASTER CLK SRC  OFF     07-05-2010 12:07:32"
    
    var r = /\([0-9]+\).+?((?:[^ ]+ )* +(?:EVENT|OFF))/g;
    var m;
    while((m = r.exec(s)) != null)
      console.log(m[1]);
    

    Output:

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

    Regex: /\([0-9]+\).+?((?:[^ ]+ )* +(?:EVENT|OFF))/g

    \([0-9]+\)       #digits in parentheses followed by  
    .+?              #some characters - minimum required (non-greedy)  
    (                #start capturing 
    (?:[^ ]+ )*      #non-space characters separated by a space  
    ` +`             #more spaces (separating string and event/off - 
                     #backticks added for emphasis), followed by
    (?:EVENT|OFF)    #EVENT or OFF
    )                #stop capturing
    

提交回复
热议问题