[英]RegEx Capturing Groups in C#
我正在嘗試使用正則表達式解析文件的內容,但是我想出的模式似乎不起作用。
我要使用的正則表達式是
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);
我們可能想嘗試的一種方法是測試我們的表達式是否可以使用另一種語言。
另外,我們可能要簡化表達式:
^(.*?)([\s:]+)?{([\s\S].*)?.$
我們有三個捕獲組。 第一個和第三個是我們想要的鍵和值。
您可以在regex101.com中修改/簡化/更改您的表達式。
您還可以在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.