Home > Software engineering >  Grabbing numbers from a string if it starts with a certain letter
Grabbing numbers from a string if it starts with a certain letter

Time:07-28

I'm hoping someone here can help me with this. If I have a string that starts with the Letter "S" and is followed by a number that's up to 8 digits long, is it possible to grab the digits afterwards?

So let's say if I have a string "blah blah blah blah S124 blah", how can I put the 124 in an int variable?

CodePudding user response:

You could do this with regular expressions (Regex).

In this case, it would be something like:

// Matches letter S and numbers from 1 up to 8 times and encapsulates numbers in group
S(\d{1,8})

And you could extract from the Match for getting the digits.

Regex numberRegex = Regex(regexString);
Match m = numberRegex.Match(stringToMatch);

String onlyNumbers = m.Groups[1].Value;

After that convert it to numbers

int number = int.Parse(onlyNumbers)

CodePudding user response:

You can try this to avoid groups

Regex.Match(input,@"(?<=S)\d{1,8}\b").Value;
  •  Tags:  
  • c#
  • Related