Reputation: 133
I have to get a little piece of a String, something like this:
20T41
Always are two numbers, a letter and numbers.
But I have many different chains like these:
I have used some codes like this, but I don't know how I can do this for each case. I think it is better than using many IFs.
str = str.Substring (0, str.LastIndexOf ('/') + 1);
Marked in black is the String I want to get. I was thinking of doing something if, but this is not efficient. What do you recommend to do this?
Upvotes: 1
Views: 126
Reputation: 23228
The following Regex
expression will also help
var regex = new Regex("\\d{2}\\w\\d+");
var input = new List<string>()
{"PNC 20T17", "PNC 19T1391", "P.N.C 19T1456,", "NC - 19T1099", "PNC 19T323", "19T1512."};
foreach (var item in input)
{
var match = regex.Match(item);
Console.WriteLine(match);
}
It produces the following output
20T17
19T1391
19T1456
19T1099
19T323
19T1512
You can have a look at quick reference
to see the meaning of every class inside
\d{2}
decimal digit, two times exactly \w
any word character, capital or not\d+
decimal digit one or more times. You can change it to \d{1,}
or \d{2,}
. It means matching the digit at least one or two times, without upper bounds, which isn't specified in OP. Or use upper bounds, like \d{1,9}
Upvotes: 1
Reputation: 4344
IF the examples you provided are all combinations then LastIndexOf
and Substring
would do the work;
var yourInput = "P.N.C 19T1456";
var res = yourInput.Substring(yourInput.LastIndexOf(' ') + 1) ;
Upvotes: 0
Reputation: 186668
You can try matching the fragment with a help of regular expressions:
using System.Text.RegularExpressions;
...
str = Regex.Match(str, "[0-9]{2}T[0-9]+").Value;
Or in case of any (not necessary T
) capital letter can appear:
str = Regex.Match(str, "[0-9]{2}[A-Z][0-9]+").Value;
Upvotes: 8