Regex to match positive and negative numbers and text between "" after a character

Viewed 212

I need a regex for an input that contains positive and negative numbers and sometimes a string between " and ". I'm not sure if this can be done in only one pattern. Here's some test cases for the pattern:

*PATH "C:\Users\User\Desktop\Media\SoundBanks\Ambient\WAV_Data\AD_SMP_SFX_WIND0.wav"
*NODECOLOR 0 255 140
*FILEREF -7
*FREQUENCY 22050

The idea would be to use a pattern that returns:

C:\Users\User\Desktop\Media\SoundBanks\Ambient\WAV_Data\AD_SMP_SFX_WIND0.wav

0 255 140

-7

22050

The content always goes after the character *. I've split this in two patterns because I don't know how to do it all in one, but doesn't work:

MatchCollection NumberMtaches = Regex.Matches(FileLine, @"(?<=[*])-?[0-9]+");
MatchCollection FilePathMatches = Regex.Matches(FileLine, @"/,([^,]*)(?=,)/g");
1 Answers

You may read the file into a string and run the following regex:

var matches = Regex.Matches(filecontents, @"(?m)^\*\w+[\s-[\r\n]]*""?(.*?)""?\r?$")
            .Cast<Match>()
            .Select(x => x.Groups[1].Value)
            .ToList();

See the .NET regex demo.

Details:

  • (?m) - RegexOptions.Multiline option on
  • ^ - start of a line
  • \* - a * char
  • \w+ - one or more word chars
  • [\s-[\r\n]]* - zero or more whitespaces other than CR and LF
  • "? - an optional " char
  • (.*?) - Group 1: any zero or more chars other than an LF char, as few as possible
  • "? - an optional " char
  • \r? - an optional CR
  • $ - end of a line/string.
Related