I need to extract a ticket number from a string. Example of the string:
string body = "Hello, world welcome. [TKNM-1234] Blah blah [HelpCode-5] Blah blah";
I need to extract ONLY 1234
from that string. What is the best way to do this. I was previously trying this:
int from = body.IndexOf("[TKNM-") + "[TKNM-".Length;
int to = body.LastIndexOf("]");
ticketNumber = body.Substring(from, to - from);
But this was having issues due to the other brackets after TKNM. Everything is in C#.
Here's a Linq Solution, this will detect multiple occurrences as well, if you dont want it discard the rest and take first OR can make it generic function if the ticket prefixes are dynamic and add them as input to function:
var body = "Hello, world welcome. [TKNM-1234] Blah blah [HelpCode-5] Blah blah";
var ticketnumbers = body.Split()
.Where(x => x.StartsWith("[TKNM") && x.EndsWith("]"))
.Select(x=>x.Replace("[", string.Empty).Replace("]", string.Empty).Split('-')[1]).ToList();
Console.WriteLine(string.Join(", ", ticketnumbers));
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.