Raj De Inno Raj De Inno - 21 days ago 6
C# Question

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

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.

Answer

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.