简体   繁体   English

如何从数字和文本C#包围的字符串中提取特定数字

[英]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. 我正在尝试以“ Q23-00000012-A14”格式提取字符串中的特定数字,我只想获取8位数字00000000中的数字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. 但是我得到230000001214的结果,我只想得到12而忽略其余的。 Can someone guide me. 有人可以指导我。

If your string are always in this format (numbers are covered with "-"), I suggest useing string.split() 如果您的字符串始终采用这种格式(数字用“-”覆盖),则建议使用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 '-' 当您使用rx.split('-')时,它会将字符串分成字符串数组,并在'-'之前和之后分配拆分文本的值

So in this case: 因此,在这种情况下:

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

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

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

So you shouldn't use Replace. 因此,您不应使用“替换”。 Use Match instead. 改用Match

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) (我认为这是使用拆分方法的更好方法,因为如果更改常量“ Q23”的长度,该方法仍然有效)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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