Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that gets the last set of numbers from a string

Tags:

c#

regex

"abc_d1.txt" should get 0
"abc_d1_2.txt" should get 2
"abc_d1_14.txt" should get 14
"abc_d12_x2_156.txt" should get 156

This is what I've done so far, but I am not getting the right result.

  string y = "tester_yg1.txt";
  string pattern = @"(\d+)(?!.*\d)";
  Regex rg = new Regex(pattern);
  var z = rg.Match(fullFileName).Value;
  Console.WriteLine($"z is {z}");
like image 561
user10860402 Avatar asked Dec 05 '25 06:12

user10860402


1 Answers

Another option is to use a single set of positive lookarounds

(?<=_[^\W\d_]\d+_?)\d*(?=\.\w+$)

Explanation

  • (?<= Positive lookbehind, assert what is directly to the left is
    • _[^\W\d_]\d+_? Match _, a word char except digits or _ and 1+ digits followed by an optional _
  • ) Close lookbehind
  • \d* Match 0+ digits (to also get the position when there is no digit)
  • (?= Positive lookahead, assert what is directly to the right is
    • \.\w+$ Match a . and 1+ word characters till the end of string
  • ) Close lookahead

.NET regex demo

enter image description here

like image 103
The fourth bird Avatar answered Dec 07 '25 21:12

The fourth bird



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!