Regex FTW! On Wed, Mar 10, 2010 at 12:09 PM, Mark Hurd <[email protected]> wrote:
> On Wed, Mar 10, 2010 at 1:16 PM, Michael Minutillo > <[email protected]> wrote: > > Cartoon swearing ahoy. > > var input = "%KEY1, value1 %KEY2,value2 %KEY3, %NOTE,This is a note > %NAME, > > Fred Knuckle"; > > var regex = @"\s*%(?<KEY>[^,]+),\s*(?<VALUE>[^%]*)"; > > var matches = Regex.Matches(input, regex); > > foreach(Match match in matches) > > { > > Console.WriteLine("{0}: {1}", match.Groups["KEY"].Value, > > match.Groups["VALUE"].Value); > > } > > Prints: > > > > KEY1: value1 > > KEY2: value2 > > KEY3: > > NOTE: This is a note > > NAME: Fred Knuckle > > Note that if you change this to: > Console.WriteLine("'{0}': '{1}'", match.Groups["KEY"].Value, > match.Groups["VALUE"].Value); > you get: > 'KEY1': 'value1 ' > 'KEY2': 'value2 ' > 'KEY3': '' > 'NOTE': 'This is a note ' > 'NAME': 'Fred Knuckle' > > To remove the extraneous spaces at the end of value, change the regex > to this (only changes near the end): > @"\s*%(?<KEY>[^,]+),\s*(?<VALUE>[^%]*?)\s*(?=%|$)" > > Now the output is: > 'KEY1': 'value1' > 'KEY2': 'value2' > 'KEY3': '' > 'NOTE': 'This is a note' > 'NAME': 'Fred Knuckle' > > -- > Regards, > Mark Hurd, B.Sc.(Ma.)(Hons.) > > > > On Wed, Mar 10, 2010 at 10:24 AM, Greg Keogh <[email protected]> wrote: > >> > >> Folks, one thing I find I have to do more often lately is parse repeated > >> keywork+value pairs, and I can’t figure out how to craft the right regex > >> pattern for this sort of thing (assuming regex can do it). I have > something > >> like this sample: > >> > >> %KEY1, value1 %KEY2,value2 %KEY3, %NOTE,This is a note %NAME, Fred > >> Knuckle > >> > >> The red chars are the keywords, each keyword is followed by an optional > >> value. Spaces can appear randomly. I’m hoping there’s some way of > parsing > >> out these pieces: > >> > >> "KEY1" > >> > >> "value1" > >> > >> "KEY2" > >> > >> "value2" > >> > >> "KEY3" > >> > >> "" > >> > >> "NOTE" > >> > >> "This is a note" > >> > >> "NAME" > >> > >> "Fred Knuckle" > >> > >> > >> Sorry for the boring looking question, but if I can find a way of > parsing > >> “repeated patterns” like my sample then it will solve a general problem > >> that’s been irritating me for ages, and the regex technique might be of > >> general use to others. > >> > >> Cheers, > >> > >> Greg > > -- > > Michael M. Minutillo > > Indiscriminate Information Sponge > > Blog: http://wolfbyte-net.blogspot.com > -- Michael M. Minutillo Indiscriminate Information Sponge Blog: http://wolfbyte-net.blogspot.com
