George of Jungle
George of Jungle

Reputation: 45

How to extract specific number in a string surrounded by numbers and text C#

I am trying to extract specific number in a string with a format of "Q23-00000012-A14" I only wanted to get the numbers in 8 digit 00000000 the 12.

string rx = "Q23-00000012-A14"
string numb = Regex.Replace(rx, @"\D", "");
txtResult.Text = numb;

But im getting the result of 230000001214, I only want to get the 12 and disregard the rest. Can someone guide me.

Upvotes: 1

Views: 779

Answers (3)

Poomrokc The 3years
Poomrokc The 3years

Reputation: 1099

If your string are always in this format (numbers are covered with "-"), I suggest useing string.split()

 string rx = "Q23-00000012-A14"
 string numb = int.parse(rx.Split('-')[1]).ToString();//this will get 12 for you

 txtResult.Text = numb;

It's an easier way than using regex

Edit!! When you use rx.split('-') , it break string into array of strings with value of splited texts before and after '-'

So in this case:

rx.Split('-')[0]= "Q23"

rx.Split('-')[1]= "00000012"

rx.Split('-')[2]= "A12"

Upvotes: 9

Perfect28
Perfect28

Reputation: 11317

So you shouldn't use Replace. Use Match instead.

string pattern = @"[A-Z]\d+-(\d+)-[A-Z]\d+" ; 

var regex = new Regex(pattern);
var match = regex.Match("Q23-00000012-A14");
if (match.Success)
{
     String eightNumberString = match.Groups[1].Value;  // Contains "00000012" 
     int yourvalueAsInt = Convert.ToInt32(eightNumberString) ; // Contains 12
}

Upvotes: 4

binard
binard

Reputation: 1784

Why you use don't simply substring or split function ?

string rx = "Q23-00000012-A14";

// substring
int numb = int.Parse(rx.Substring(5, 8));

// or split
int numb = int.Parse(rx.Split('-')[1]);


txtResult.Text = numb.ToString();

(I think it's a better way to use split method because if you change your constant 'Q23' length the method still work)

Upvotes: 2

Related Questions