【问题标题】:Regex based on THIS or THAT基于 THIS 或 THAT 的正则表达式
【发布时间】:2017-07-24 21:09:59
【问题描述】:

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

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

我明白我在这里做错了什么。第 1 组返回整行,第 2 组返回 (#.*),如果行以 # 开头,否则返回 null,第 3 组返回 ([^=]+=(.+)。| 是什么我正在尝试。我想根据 EITHER 第二组

的条件来解析它
(#.*)

第三组

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

怎么做?

编辑:错误的示例代码

【问题讨论】:

  • 您在问题中提到了管道字符,但没有解释您遇到的问题。

标签: java regex token delimiter


【解决方案1】:

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

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

RegEx Demo

RegEx 拆分:

  • (?m):开启MULTILINE模式
  • ^(#.*):匹配 #1 组中以 # 开头的整行
  • |: 或者
  • ^([^=]+)=:匹配到 = 并在第 2 组中捕获,然后是 =
  • (.*): 匹配组 #3 中的其余行

【讨论】:

  • 您在 RegEx 演示中的回答是正确的,但不是您在此处发布的内容。谢谢!你能解释一下 (?:) 表达式在这里做什么。我做了一些阅读,我收集到的是,之后捕获的任何内容都不会被存储,但是你用这个包裹了整条线,所以整条线都不会被捕获?
  • 你收到最近的评论了吗?
  • (?:..) 被称为非捕获组。
  • 感谢您的帮助。
猜你喜欢
  • 2021-10-01
  • 2011-05-23
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多