3

我正在尝试匹配等号周围的字符串中的文本。
我的正则表达式是这样的:( "((?:\\S+\\s)?\\S*=)(\\S*(?:\\s\\S+)?)"因为\\C# 不喜欢使用未转义的 '\' 字符串)。

给定字符串"the thing=12 and otherthing = 'thirty'",它将返回以下组:“the thing="、"12 and"、"otherthing=" 和 "'thirty'"。

我不擅长正则表达式,我不确定下一步该做什么。
我需要它来返回以下组:“thing”、“12”、“otherthing”和“thirty”(注意“thirty”中去掉了单引号)。

谁能帮我这个?似乎 C# Regex 解析器与 gskinner.com 上的解析器不同,因为我认为我有一些这样的工作,但它在 C# 中没有。

4

3 回答 3

2

也许是这样的?

string input = "bob = 20 joe=thirty";
var regex = new Regex(@"(?<left>[^=]+?)\s+=\s+(?<right>[^\s]+)");
foreach(Match match in regex.Matches(input))
{
    Console.WriteLine("{0} = {1}", 
        match.Groups["left"].Value,
        match.Groups["right"].Value);
}
于 2012-12-20T23:11:57.300 回答
1

此模式采用 the 之前的第一个单词(连续的非空格)=和后面的引用值或第一个单词。

@"(?<name>[^ =]+?)\s*=\s*('(?<value>[^']+)'|(?<value>[^\s]+))"

(在 C# 中,通常最好对正则表达式使用文字字符串@"\s",因为您只需要转义双引号。 @"\s""" == "\\s\""

var pattern = @"(?<name>[^ =]+?)\s*=\s*('(?<value>[^']+)'|(?<value>[^\s]+))";
var s = "the thing=12 and otherthing = 'thirty'";
foreach(Match match in Regex.Matches(s, pattern))
   Console.WriteLine("{0} = {1}", 
      match.Groups["name"].Value,
      match.Groups["value"].Value);

对于the thing=12 and otherthing = 'thirty',它产生:

thing = 12
otherthing = thirty
于 2012-12-21T02:58:39.587 回答
0

这听起来像是String.Split的工作。如果您确定需要正则表达式,则可以使用Regex.Split

于 2012-12-20T23:08:22.773 回答