Reputation: 69
I have a specific pattern I want to follow but the extraction process is not working as expected. I assume the pattern I developed is not correct, but I can't find the issue in it.
I have the string string test1 = "R1 0.1uF"
and the pattern
"(?<des>^[a-zA-Z]+)|(?<number>\d+\s+)|(?<val>[0-9]*.?[0-9]+)|(?<units>[^,]*)";
I want it to be extracted as follows:
des: R
number: 1
val: 0.1
units: uF
Currently, des
is working properly and it's finding R
but the others return an empty string.
Here's my code
const string pattern = @"(?<des>^[a-zA-Z]+)|(?<number>\d+\s+)|(?<val>[0-9]*.?[0-9]+)|(?<units>[^,]*)";
string test1 = "R1 0.1uF";
Regex r = new Regex(pattern, RegexOptions.Compiled);
Match m = r.Match(test1);
string des = m.Groups["des"].Value;
string number = m.Groups["number"].Value;
string val = m.Groups["val"].Value;
string units = m.Groups["units"].Value;
Upvotes: 1
Views: 75
Reputation: 2892
Two comments:
|
s because you don't want to match des OR number OR val OR units
but des followed by number followed by val followed by units
\.
because you want to match a dot, not some random character.So, your regex becomes
(?<des>^[a-zA-Z]+)(?<number>\d+\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)
Look at regex101
Some little improvements, if I may:
^
to the front. It doesn't belong in the first group.Like this:
^(?<des>[a-zA-Z]+)(?:(?<number>\d+)\s+)(?<val>[0-9]*\.?[0-9]+)(?<units>[^,]*)
See regex101
Upvotes: 3