开发者

Why is this Regular expression working in RegexBuddy but not in .NET

Is there reason following should not work in via .Net but works in RegexBuddy?

String:

formatter:'number',formatoptions:{decimalSeparator:'.',decimalPlaces:2,defaulValue:0}

Expression pattern:

[a-zA-Z]+:({)??([a-zA-Z]+[:](')??[a-zA-Z0-9.,]+(?(3)'|,?),?)+(?(1)}|.)

Produces matches within regex buddy but fail within .net.

private static List<string> GetObjectProps(this string str, out string strWithOutObjectProps)
{
    var lst = new List<String>();
    var temp = str;
    Regex RegexObj = new Regex("[a-zA-Z]+:({)??([a-zA-Z]+[:](')??[a-zA-Z0-9.,]+(?(3)'|,?),?)+(?(1)}|.)");
    Match MatchResults = RegexObj.Match(str);

    while(MatchResults.Success) //fails
    {
        lst.Add(MatchResults.Value);
        temp = MatchResults.Index > 0
                   ? temp.Substring(0, MatchResults.Index - 1) +
                     temp.Substring(MatchResults.Index + MatchResults.Length)
                   : temp.Substring(MatchResults.Index + MatchResults.Length);

        MatchResults = MatchResults.NextMatch();
    }

    strWithOutObjectProps = temp;
    return lst;
}

Solution !

Turns out this conflict was on a/c of older regexbuddy, latest version pointed out the error for .net simulation as well.

Reworked Expression :

new Regex(@"\s?\b[a-zA-Z]+\b:\{
           (?:
             \b[a-zA-Z]+\b:
             (?:[0-9]+|'[.,]?'|'[\w]+'),?
           )+
           \}",
           Re开发者_StackOverflow中文版gexOptions.IgnorePatternWhitespace);

Allthough this expression is not perfect on a/c of having to make the delimiter optional so as to avoid the trailing delimiter, any ideas so as how to avoid this ?


I know that RegexBuddy emulates the .NET Regex engine. It doesn't actually run it directly. The limitations include a lack of support for balancing groups, for example. But you may have just stumbled across some other incompatibility. You may want to contact them about it or post on their forum so they can look into it.

As a test you can also try the regular expression with Regex Hero which runs directly off of the .NET Regex engine.


After a bit of tweaking this is what I came up with:

var reg = new Regex("\s+(?<name>[a-zA-Z]*)\s+:\s+(?<value>('.*')|(\".*\")|[^,}]*)");
var input = "{ decimalSeparator : \",\", decimalPlaces : 2, defaulValue : 0 }";
var matches = reg.Matches(input);
var name = matches[0].Groups["name"];
var value = matches[0].Groups["value"];

I made a few assumptions about what you wanted so let me know if they are wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜