Regex based on THIS or THAT

[亡魂溺海] 提交于 2019-12-11 06:36:07

问题


I am trying to parse the below:

"#SenderCompID=something\n" +
"TargetCompID=something1"

into an array of:

{"#SenderCompID=something", "TargetCompId", "something1"}

Using:

String regex = "(?m)" + "(" +     
    "(#.*) |" +                //single line of (?m)((#.*)|([^=]+=(.+))
    "([^=]+)=(.+) + ")";
String toMatch = "#SenderCompID=something\n" +
    "TargetCompID=something1";

which is outputting:

#SenderCompID=something
null
#SenderCompID
something
                       //why is there any empty line here?
TargetCompID=something1
null
                       //why is there an empty line here?
TargetCompID
something1

I understand what I'm doing wrong here. The 1st group is returning the entire line, the 2nd group is returning (#.*) if the line starts with # and null otherwise, the 3rd group is returning ([^=]+=(.+). The | is what I'm trying to do. I want to parse it based on EITHER the conditions for the 2nd group

(#.*)

or for the 3rd group

([^=]+)=(.+).

How?

EDIT: miswrote example code


回答1:


You can use this regex to get all 3 groups:

(?m)^(#.*)|^([^=]+)=(.*)

RegEx Demo

RegEx Breakup:

  • (?m): Enable MULTILINE mode
  • ^(#.*): match a full line starting with # in group #1
  • |: OR
  • ^([^=]+)=: Match till = and capture in group #2 followed by =
  • (.*): Match rest of line in group #3


来源:https://stackoverflow.com/questions/45290104/regex-based-on-this-or-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!