简体   繁体   中英

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)

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

Pattern

\(([^)]*)\)

Example Usage

  Regex.Match("Test(99)", @"\(([^)]*)\)").Groups[1].Value

If your number is always an Integer you can use Regex for it

var resultNumber = Regex.Match(values.SelectedText, @"\d+").Value;

and then use int.parse

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