当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - .NET Regex issue, also .NET regex uses a different rule engine?

问题描述:

I'm trying to match text in a string around an equals sign.

My regex is this: "((?:\\S+\\s)?\\S*=)(\\S*(?:\\s\\S+)?)" (the \\ are there because C# doesn't like to use the '\' string unescaped).

Given the string "the thing=12 and otherthing = 'thirty'" this returns groups of: "the thing=", "12 and", "otherthing =" and "'thirty'".

I am bad at Regex and I'm not sure what to do next.

I need this to return groups of: "thing", "12", "otherthing" and "thirty" (notice the stripped out single quotes in "thirty").

Can anyone help me with this? It seems like the C# Regex parser is different than the one on gskinner.com as I thought I had some of this working but it doesn't in C#.

网友答案:

This pattern takes the first word (consecutive non-spaces) before the = and the following quoted value or first word.

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

(In C#, it is often best to use a literal string @"\s" for regexs because you only need to escape double-quotes. @"\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);

For the thing=12 and otherthing = 'thirty', it yields:

thing = 12
otherthing = thirty
网友答案:

Maybe something like this?

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);
}
网友答案:

This sounds like a job for String.Split. If you're certain you need regex, you can use Regex.Split.

分享给朋友:
您可能感兴趣的文章:
随机阅读: