[英]Extract number from a formatted string(dropdownlist)
So I'm trying to extract an integer from a string(selectedtext from dropdownlist) using substring. 所以我试图使用子字符串从字符串(从下拉列表中选择文本)中提取一个整数。 The number is between parenthesis, this is my code, but it keeps saying length cannot be zero, which I guess means that it can't find the parenthesis, even though they are there.
数字在括号之间,这是我的代码,但一直说长度不能为零,我想这意味着即使有括号也无法找到括号。 An example of a value from my dropdownlist would be Test(99) or Teehee(1)
我的下拉列表中的一个值示例是Test(99)或Teehee(1)
int selectedValue = int.Parse(values.SelectedText.Substring(values.SelectedText.IndexOf("(") + 1, values.SelectedText.IndexOf(")") - values.SelectedText.IndexOf("(") - 1)));
You should use a regular expression for this. 您应该为此使用正则表达式。
Pattern Demonstration 模式演示
https://regex101.com/r/gH3xK2/1 https://regex101.com/r/gH3xK2/1
Pattern 图案
\(([^)]*)\)
Example Usage 用法示例
Regex.Match("Test(99)", @"\(([^)]*)\)").Groups[1].Value
If your number is always an Integer you can use Regex
for it 如果您的电话号码始终是整数,则可以使用正则
Regex
var resultNumber = Regex.Match(values.SelectedText, @"\d+").Value;
and then use int.parse
然后使用
int.parse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.