jason
jason

Reputation: 7164

Get number from a string which also includes datetime in C#

I have this string :

Ümraniye Tapu Müdürlüğünde ve Ümraniye Belediyesi İmar Müdürlüğünde 20.08.2014 onay tarih ve 254 sayılı mimari projesi incelenmiştir.

I'm getting datetime : like this :

t = DateTime.Parse(Regex.Match(mimaristring, @"\d(\d+)[-.\/](\d+)[-.\/](\d+)").Value);

I'm trying to get 254 like this :

num = Regex.Match(mimaristring, @"\d+").Value;

But instead of 254, I get 20. How can I skip datetime and get 254?

NOTE: Sometimes, I have numbers like 123/456, not just 254, and I need to get them, too.

Upvotes: 1

Views: 106

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

To get the whole number not inside dots+digits, you need to use lookarounds:

@"(?<!\d\.)\b\d+(?:/\d+)?\b(?!\.\d)"

See this regex demo

Pattern explanation:

  • (?<!\d\.) - no match if there is a digit+. before the current location
  • \b - a word boundary
  • \d+(?:/\d+)? - 1+ digits optionally followed with / and 1+ digits
  • \b - a trailing word boundary
  • (?!\.\d) - fail the match if there is a dot followed with a digit.

C# demo:

var s = "Ümraniye Tapu Müdürlüğünde ve Ümraniye Belediyesi İmar Müdürlüğünde 20.08.2014 onay tarih ve 254 sayılı mimari projesi incelenmiştir.";
var pat = @"(?<!\d\.)\b\d+(?:/\d+)?\b(?!\.\d)";
Console.WriteLine(Regex.Match(s, pat).Value);

Upvotes: 2

Related Questions