基于THIS或THAT的正则表达式 [英] Regex based on THIS or THAT

查看:83
本文介绍了基于THIS或THAT的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析以下内容:

I am trying to parse the below:

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

放入数组:

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

使用:

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

正在输出:

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

我知道我在做什么这里错了第一组是返回整行,如果该行以#开头,则第二组返回(#。*),否则返回null,否则,第三组返回([^ =] + =(。+)。 |这就是我想要做的。我想根据第二组的条件来解析它

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

(#.*)

或用于第三组

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

如何?

编辑:错误地编写了示例代码

miswrote example code

推荐答案

您可以使用此正则表达式获取所有3个组:

You can use this regex to get all 3 groups:

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

RegEx演示

正则表达式分解:


  • (?m):启用 MULTILINE 模式

  • ^(#。*):匹配#1组中以开头的整行

  • | :或

  • ^([^ =] +)= :匹配到 = 并捕获到#2组中,然后捕获 =

  • (。*):匹配#3组中的其余行

  • (?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

这篇关于基于THIS或THAT的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆