tags:

views:

55

answers:

3

Hello,

I am a regex idiot and never found a good tutorial (links welcome, as well as a pointer to an interactive VS2010 integrated editor).

I need to parse strings in the following form:

[a/b]:c/d

a, b: double with "." as possible separator. CAN be empty
c: double with "." as separator
d: integer, positive

I.e. valid strings are:

[/]:0.25/2
[-0.5/0.5]:0.05/2
[/0.1]:0.05/2

;) Anyone can help?

Thanks

+3  A: 
^\[(-?\d+\.?\d+?)?/(-?\d+\.?\d+?)?\]:(-?\d+\.?\d+?)/(\d+)$

captures each number in its own group.

This assumes that it's legal for your double values not to contain a decimal part. If it isn't, you can use

^\[(-?\d+\.\d+)?/(-?\d+\.\d+)?\]:(-?\d+\.\d+)/(\d+)$
Tim Pietzcker
+1  A: 
var match = Regex.Match("[-0.5/0.5]:0.05/2", @"\[([\.\-0-9]*)/([\.\-0-9]*)\]:([\.\-0-9]*)/([\.\-0-9]*)");
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
    Console.WriteLine(match.Groups[2].Value);
    Console.WriteLine(match.Groups[3].Value);
    Console.WriteLine(match.Groups[4].Value);
}
Darin Dimitrov
Can sadly only choose one answer as answer ;) Thanks for the code sample.
TomTom
+1  A: 

There's a regex editor on the Visual Studio Gallery:
http://visualstudiogallery.msdn.microsoft.com/en-us/55c24bf1-2636-4f94-831d-28db8505ce00

It's not widely known, but it's possible to put whitespace and comments in your regexes. This can make a regex like these much more readable. Here's an example based on Tim Pietzcker's first answer:

var regex = @"(?x:
    ^                   # Anchor to start of string
    \[                  # [
        (-?\d+\.?\d+?)? # a - double
    /                   # /
        (-?\d+\.?\d+?)? # b - double
    \]                  # ]
    :                   # Literal colon character
        (-?\d+\.?\d+?)  # c - double
    /                   # /
        (\d+)           # d - integer
    $                   # Anchor to end of string
)";
Damian Powell