Search code examples
c#regexmatchstring-matching

Why regexp does not find match


Code

var tekst = "Sum km-ta 20% _48,15";
var rida = Regex.Match(tekst, @"(?si)Sum(_)?(\skm-ta)?(\s)?(20%)?(:)?(\s)?(_)?(?<kmta>.*?)\s", RegexOptions.Singleline);

Does not find math. It looks like RegExp is correct but for unknown reason sum is not found. How to get match 48,15 ?

Using C# in .NET 7


Solution

  • The problem is that kmta group is lazy, so empty match is fine. You can try to limit what is allowed inside the group and remove laziness, also there is no invisible characters at the end of the string - (?si)Sum(_)?(\skm-ta)?(\s)?(20%)?(:)?(\s)?(_)?(?<kmta>[\d,\.]*)(\s)?:

    var tekst = "Sum km-ta 20% _48,15";
    var rida = Regex.Match(tekst, @"(?si)Sum(_)?(\skm-ta)?(\s)?(20%)?(:)?(\s)?(_)?(?<kmta>[\d,\.]*)(\s)?", RegexOptions.Singleline);
    var ridaGroup = rida.Groups["kmta"].Value; // 48,15
    

    Also you can just remove laziness and make the \s optional: (?si)Sum(_)?(\skm-ta)?(\s)?(20%)?(:)?(\s)?(_)?(?<kmta>.*)\s?