Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regular expression match

Tags:

c#

regex

18.jun. 7 noči od 515,00 EUR

here I would like to get 515,00 with a regular expression.

Regex regularExpr = new Regex(@rule.RegularExpression,
                              RegexOptions.Compiled | RegexOptions.Multiline |
                              RegexOptions.IgnoreCase | RegexOptions.Singleline |
                              RegexOptions.IgnorePatternWhitespace);

tagValue.Value = "18.jun. 7 noči od 515,00 EUR";
Match match = regularExpr.Match(tagValue.Value);

object value = match.Groups[2].Value;

regex is: \d+((.\d+)+(,\d+)?)?

but I always get an empty string (""). If I try this regex in Expresso I get an array of 3 values and the third is 515,00.

What is wrong with my C# code that I get an empty string?

like image 370
senzacionale Avatar asked Mar 02 '26 03:03

senzacionale


1 Answers

Your regex matches the 18 (since the decimal parts are optional), and match.Groups[2] refers to the second capturing parenthesis (.\d+) which should correctly read (\.\d+) and hasn't participated in the match, therefore the empty string is returned.

You need to correct your regex and iterate over the results:

StringCollection resultList = new StringCollection();
Regex regexObj = new Regex(@"\d+(?:[.,]\d+)?");
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    resultList.Add(matchResult.Value);
    matchResult = matchResult.NextMatch();
} 

resultList[2] will then contain your match.

like image 135
Tim Pietzcker Avatar answered Mar 04 '26 15:03

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!