【问题标题】:RegEx Capturing Groups in C#C# 中的正则表达式捕获组
【发布时间】:2019-10-05 10:53:51
【问题描述】:

我正在尝试使用正则表达式解析文件的内容,但我想出的模式似乎不起作用。

我尝试使用的正则表达式是

string regex = @"^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$";

我试图解析它的文本是

string text = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:{val-u{0}e}
key:{val__[!]
-u{0}{1}e}";

但是,它返回 0 个结果

MatchCollection matches = Regex.Matches(text, regex, RegexOptions.Multiline);

我已尝试在 RegExr 上测试此正则表达式,它按预期工作。
我不确定为什么在 C# 中尝试它时这不起作用。

MCVE:

string regex = @"^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$";
string text = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:{val-u{0}e}
key:{val__[!]
-u{0}{1}e}";
MatchCollection matches = Regex.Matches(text, regex, RegexOptions.Multiline);
Console.WriteLine(matches.Count);

【问题讨论】:

  • 正如 Luuk 所指出的,您提供的正则表达式适用于您提供的文本。请提供一个minimal reproducible example 来说明问题。
  • @jonskeet 此处使用正则表达式:github.com/SMLHelper/SMLHelper/blob/LangOverrideBug/SMLHelper/… 至于 mcve,我已经更新了我原来的问题
  • 正确 - 该代码打印 1,而不是 0。所以请提供一个 实际上 打印 0 的示例...或者如果您处于不寻常的环境中(可能有一个损坏的正则表达式实现)请提供详细信息。
  • 至少,它使用 CR/LF 换行符在我的 Windows 机器上打印 1。如果将其更改为仅 LF 换行符,则会打印 5。

标签: c# regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

我们可能想尝试的一种方法是测试我们的表达式是否适用于另一种语言。

另外,我们可能想要简化我们的表达式:

^(.*?)([\s:]+)?{([\s\S].*)?.$

我们有三个捕获组。第一个和第三个是我们想要的键和值。

正则表达式

您可以在regex101.com 中修改/简化/更改您的表达方式。

正则表达式电路

您还可以在jex.im 中可视化您的表达式:

JavaScript 演示

const regex = /^(.*?)([\s:]+)?{([\s\S].*)?.$/gm;
const str = `key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:   {val-u{0}e}
key:  {val__[!]
-u{0}{1}e}`;
const subst = `$1,$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

C# 测试

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^(.*?)([\s:]+)?{([\s\S].*)?.$";
        string substitution = @"$1,$3";
        string input = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:   {val-u{0}e}
key:  {val__[!]
-u{0}{1}e}";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

原始正则表达式测试

const regex = /^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$/gm;
const str = `key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:   {val-u{0}e}
key:  {val__[!]
-u{0}{1}e}`;
const subst = `$1,$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2021-08-02
    • 2018-03-11
    • 1970-01-01
    相关资源
    最近更新 更多