Regex在Regexr中工作,但不是在C#,为什么?
从下面提到的输入字符串中,我想提取{}中为s:ds字段指定的值。我已附上我的正则表达式模式。现在,我用于测试的模式是: 而且它工作得非常好 但在C#代码中,同样的方法不起作用。我还为c代码添加了\\而不是\并将\“替换为\”。如果我做错了,请告诉我。下面是代码片段Regex在Regexr中工作,但不是在C#,为什么?,c#,regex,C#,Regex,从下面提到的输入字符串中,我想提取{}中为s:ds字段指定的值。我已附上我的正则表达式模式。现在,我用于测试的模式是: 而且它工作得非常好 但在C#代码中,同样的方法不起作用。我还为c代码添加了\\而不是\并将\“替换为\”。如果我做错了,请告诉我。下面是代码片段 string inputString is "s:ds=\"{46C01EB7-6D43-4E2A-9267-608DE8AFA311}\" s:ds=\"{37BA4BA0-581C-40DC-A542-FFD9E99BC345}\
string inputString is "s:ds=\"{46C01EB7-6D43-4E2A-9267-608DE8AFA311}\" s:ds=\"{37BA4BA0-581C-40DC-A542-FFD9E99BC345}\" s:id=\"{C091E71D-4817-49BC-B120-56CE88BC52C2}\"";
string regex = @"s:ds=\\\""({[\d\w]{8}\-(?:[\d\w]{4}\-){3}[\d\w]{12}})\\\""";
MatchCollection matchCollection = Regex.Matches(layoutField, regex);
if (matchCollection.Count > 1)
{
Log.Info("Collection Found.", this);
}
如果您只观察匹配的值… 如果您只想与您的鸥翼大括号匹配,您应该能够对表达式使用
([\d\w]{8}-([\d\w]{4}-){3}[\d\w]{12})
:
string input = "s:ds=\"{46C01EB7-6D43-4E2A-9267-608DE8AFA311} ...";
// Use the following expression to just match your GUID values
string regex = @"([\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12})";
// Store your matches
MatchCollection matchCollection = Regex.Matches(input, regex);
// Iterate through each one
foreach(var match in matchCollection)
{
// Output the match
Console.WriteLine("Collection Found : {0}", match);
}
您可以使用下面演示的示例和输出:
如果您只想匹配以下s:ds
…
如果您只想捕获<代码> s:ds/COD>节的值,您可以考虑追加<代码>(?看起来您可能正在越狱。
试一试:@“s:ds=\”“({[\d\w]{8}-([\d\w]{4}-){3}[\d\w]{12}})\”
是输入字符串文字反斜杠中的\
或仅是的转义符号?参见。这是一个原始输入字符串,将用于进一步的工作。因此,看一下。作为给定的输入字符串的字符。请参阅根据您的演示,ReGEX考虑输入字符串“AS”。请尝试我的解决方案和下面的一个,让我们知道哪一个为您工作。注意<代码> [\W\D]。<代码> >代码> \代码> >非常真实的Wikor。我在我的回答中添加了另一个注释:“代码> \W/COD>在这种情况下可能会有点过头,因为它将匹配<代码> 字符。如果OP想要更精确,则可以考虑使用<代码> [AZ\D]。
只匹配大写字母和数字。另外,在.NET中,\d
=\p{N}
,因此如果您想实际匹配GUID,可能需要将其替换为[0-9A-Fa-f]
。非常感谢大家的输入。
string input = "s:ds=\"{46C01EB7-6D43-4E2A-9267-608DE8AFA311} ...";
// Use the following expression to just match your GUID values
string regex = @"([\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12})";
// Store your matches
MatchCollection matchCollection = Regex.Matches(input, regex);
// Iterate through each one
foreach(var match in matchCollection)
{
// Output the match
Console.WriteLine("Collection Found : {0}", match);
}
string regex = @"(?<=(s:ds=""{))([\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12})";