Reputation: 101
I'm reading the content of a config file and then trying to parse out a specific setting:
var content = File.ReadAllText(PsdFile);
var version = Regex.Replace(content, @"ModuleVersion\s+=\s+'(\d+)\.(\d+)\.(\d+)'", "$1.$2.$3");
I have the input file set to:
ModuleVersion = '3.1.11'\r\n
This is the VS variable preview. The file contains a blank line at the end. After executing the code above, the version variable contains:
3.1.11\r\n
So it's matched and identified the capture groups correctly but some reason it is appending \r\n. I don't understand why.
It does seem to be related to the newline in the file. If I remove the newline then the newline is not appended to the replaced string. How can the final capture group match the final version triplet and the newline but exclude the single quote?
Upvotes: 2
Views: 52
Reputation: 626870
The Regex.Replace(content, @"ModuleVersion\s+=\s+'(\d+)\.(\d+)\.(\d+)'", "$1.$2.$3")
line of code performs a regex search of the ModuleVersion\s+=\s+'(\d+)\.(\d+)\.(\d+)'
pattern, that is, it search for ModuleVersion
, 1+ whitespaces, =
, 1+ whitespaces, '
, then it captures 1+ digits into Group 1, then matches a dot, then captures 1+ digits into Group 2, again matches a dot and places another 1+ digits into Group 3 and matches a '
char, and then the whole match is replaced with Group 1 value, .
, Group 2 value, .
and Group 3 value.
So, as you see, that does nothing with the line break, and it makes little sense to capture those 3 groups as you still use the dots as a separator.
What you seem to be doing is extracting a value. Use Regex.Match
to extract a single piece of text:
var version = "";
var m = Regex.Match(content, @"(?<=ModuleVersion\s+=\s+')\d+(?:\.\d+)+");
if (m.Success) {
version = m.Value;
}
See the regex demo. Here, (?<=ModuleVersion\s+=\s+')
is a lookbehind that requires ModuleVersion
, 1+ whitespaces, =
, 1+ whitespaces and '
to appear immediately to the left of the current location.
Note that you may also use a capturing approach and get the result from match.Groups[1].Value
:
var version = "";
var m = Regex.Match(content, @"ModuleVersion\s+=\s+'(\d+(?:\.\d+)+)");
if (m.Success) {
version = m.Groups[1].Value;
}
Upvotes: 2