fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5.  
  6. public class Test
  7. {
  8. public static void Main()
  9. {
  10. var l = new List<string> {"via caporale degli zuavi 278a , 78329","autostrada a1 km - 47"};
  11. foreach (var t in l)
  12. {
  13. var rx = @"^(?!.*(?<!\p{L})km\b)(?:.*\D)?(\d{1,4})(?=\p{L}?\b)";
  14. var match = Regex.Match(t, rx, RegexOptions.ECMAScript)?.Groups[1].Value;
  15. if (!string.IsNullOrEmpty(match))
  16. {
  17. Console.WriteLine($"There is a match in '{t}': {match}");
  18. }
  19. else
  20. {
  21. Console.WriteLine($"There is no match in '{t}'.");
  22. }
  23. }
  24. }
  25. }
Success #stdin #stdout 0.07s 27248KB
stdin
Standard input is empty
stdout
There is a match in 'via caporale degli zuavi 278a , 78329': 278
There is no match in 'autostrada a1 km - 47'.