[英]RegEx Capturing Groups in C#
I'm trying to parse a file's contents using regex, but the patter I came up with doesn't seem to work. 我正在尝试使用正则表达式解析文件的内容,但是我想出的模式似乎不起作用。
The regex I am trying to use is 我要使用的正则表达式是
string regex = @"^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$";
and the text i am trying to parse it against is 而我要解析的文字是
string text = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:{val-u{0}e}
key:{val__[!]
-u{0}{1}e}";
However, it returns 0 results 但是,它返回0个结果
MatchCollection matches = Regex.Matches(text, regex, RegexOptions.Multiline);
I have tried testing this regex on RegExr , which worked as expected. 我已经尝试在RegExr上测试此正则表达式,该表达式工作正常。
I am unsure why this doesn't work when trying it in C#. 我不确定为什么在C#中尝试时这不起作用。
MCVE: 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);
One way we might like to try is to test that if our expression would be working in another language. 我们可能想尝试的一种方法是测试我们的表达式是否可以使用另一种语言。
Also, we might want to simplify our expression: 另外,我们可能要简化表达式:
^(.*?)([\s:]+)?{([\s\S].*)?.$
where we have three capturing groups. 我们有三个捕获组。 The first and third ones are our desired key and values. 第一个和第三个是我们想要的键和值。
You can modify/simplify/change your expressions in regex101.com . 您可以在regex101.com中修改/简化/更改您的表达式。
You can also visualize your expressions in jex.im : 您还可以在jex.im中可视化表达式:
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);
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.