【问题标题】:Apply quantifiers on capture groups在捕获组上应用量词
【发布时间】:2013-08-15 09:07:31
【问题描述】:

请考虑以下输入字符串:

X=Y
Z=U
Q=P

Lorem Ipsum 只是印刷和排版行业的虚拟文本。
自 1500 年代以来,Lorem Ipsum 一直是业界标准的虚拟文本

我想知道是否可以使用正则表达式单行来捕获以下内容:

:X
:Y
:Z
: U
left: Q
right: P

text: Lorem Ipsum 是简单的虚拟文本印刷排版
行业。 Lorem Ipsum 一直是业界标准的虚拟文本
自 1500 年代以来

这个想法是有一堆具有特定格式的行,后跟一个“\r\n”,然后是一些文本。我想分别捕获每个键值对(在此示例中)和文本。

捕获结构化数据很容易(这里只是一个示例):

(?:^(?<left>\S+)=(?<right>\S)\n)

但我不知道如何指定如下内容:

“继续捕获此模式直到第一个空行,然后将所有内容捕获到“文本”。

使用代码解决这个问题很容易,但我真的很想知道它是否可能只使用正则表达式单行。

【问题讨论】:

  • 输出是第二个引用的文本块,但 m.buettner 的回答确实准确地解释了我想要理解的内容。

标签: .net regex


【解决方案1】:

是的,在 .NET 中(并且仅在其中)您可以重复捕获组,并从每次重复中获取捕获:

^               # anchor pattern to the beginning of the string
(?:             # non-capturing group for a single x=y line
  (?<left>\S+)  # match and capture left-hand side
  =
  (?<right>\S+) # match and capture right-hand side
  \n
)+              # repeat
\n              
(?<text>.*)     # match the remainder of the string
$               # anchor pattern to the end of the string (not really necessary)

确保使用RegexOptions.IgnorePatternWhitespaceRegexOptions.Singleline

如果您的Match 对象被称为m,那么您现在可以检索:

m.Groups["left"].Captures  // for a list of all left-hand sides
m.Groups["right"].Captures // for a list of all right-hand sides
m.Groups["text"].Value     // for the remainder of the string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多