Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the specific number from string in view of beginning whole number in c#

Tags:

c#

regex

I am attempting to get the Match an esteem from a string. I have to get two sorts of numbers from the given string. Number begins from 5 took after by 6 digits. ex(5******) and begins from 1 took after by 5 digits(1*****).

I use the following regexex:

(5)[\d]{6} 
(1)[\d]{5}

Code:

  var sampleId5 = Regex.Match(input, @"(5)[\d]{6}");
  if (sampleId5.Success)
  {
      string test = sampleId5.Value;
  }

  var sampleId1 = Regex.Match(input, @"(1)[\d]{5}");
  if (sampleId1.Success)
  {
      string test1 = sampleId1.Value;
  }

Issue here is, whether I pass 5106542 it is returning both coordinated results.

I attempted this (^5)[\d]{6} too. be that as it may, its not working.

I require just 5******. Any help would be truly valued.

like image 342
Raj De Inno Avatar asked Dec 17 '25 16:12

Raj De Inno


1 Answers

The problem is that your expressions do not make any requirements about the placement of the match, so they find matches in the middle.

If you need to find stand-alone numbers that fit your criteria, add \b on both sides of your expressions to ensure that there are no letters/digits on either side:

var sampleId1 = Regex.Match(input, @"\b(1)[\d]{5}\b");
//                                   ^^          ^^

Now that the expression considers only isolated sequences of digits, 5106542 is not going to match, because the matched sequence is in the middle.

like image 157
Sergey Kalinichenko Avatar answered Dec 19 '25 05:12

Sergey Kalinichenko



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!