I'm trying to parse some source files for some standard information.
The source files could look like this:
// Name: BoltBait
// Title: Some cool thing
or
// Name :
// Title : Another thing
or
// Title:
// Name:
etc.
The code I'm using to parse for the information looks like this:
Regex REName = new Regex(@"\/{2}\s*Name\s*:\s*(?<nlabel>.*)\n", RegexOptions.IgnoreCase);
Match mname = REName.Match(ScriptText); // entire source code file
if (mname.Success)
{
Name.Text = mname.Groups["nlabel"].Value.Trim();
}
Which works fine if the field has information. It doesn't work if the field is left blank.
For example, in the third example above, the Title
field returns a match of "// Name:" and I want it to return the empty string.
I need help from a regex expert.
I thought the regex was too greedy, so I tried the following expression:
@"\/{2}\s*Name\s*:\s*(?<nlabel>.*?)\n"
However, it didn't help.
You can also use a class subtraction to avoid matching newline symbols:
Note that:
[\s-[\r\n]]*
- Matches any whitespace excluding newline symbols (a character class subtraction is used)(?=\r?\n|$)
- A positive look-ahead that checks if there is a line break or the end of the string.See regex demo, output: