简体   繁体   中英

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.

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"

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
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM