Reputation: 69
I have a AlphaNumeric value which may contain white space or under score in it. I want to split numeric from that and increment the value by one and need to join the numeric part back to Alpha part.
For example the Alpha Numeric may be : 1- BA 123 or 2. BA_123
I used Regex , it works if the string does not contain any white spaces or under score . Here is the code used to split and increment by one:
string StrInputNumber="BA123"
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = numAlpha.Match(StrInputNumber);
var alpha = match.Groups["Alpha"].Value;
int num = int.Parse(match.Groups["Numeric"].Value);
This works only for Alpha and numeric without any special characters
Please guide to solve this issue
Upvotes: 2
Views: 1896
Reputation: 92986
You just need to add those characters at the point where you expect them.
string[] StrInputNumber = { "BA123", "BA_123", "BA 123", "Foo 1"};
foreach (String item in StrInputNumber) {
Console.Write(item + "\t==>\t");
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*[ _]?)(?<Numeric>[0-9]*)");
var match = numAlpha.Match(item);
var alpha = match.Groups["Alpha"].Value;
int num = int.Parse(match.Groups["Numeric"].Value) + 1;
Console.WriteLine(alpha + num);
}
This would allow (optionally) one space or one _
after the letters.
If you want to be more flexible, you can just add the characters in the class where the letters are.
var numAlpha = new Regex("(?<Alpha>[a-zA-Z _]*)(?<Numeric>[0-9]*)");
That would allow any amount of spaces and underscores anywhere before the digits in the string (e.g. "Foo _ bar ___ 123
" would match).
Unicode
If you want to match all letters and not only the ASCII ones, try Unicode code properties
\p{L}
would be any letter in any language
\d
is a shorthand character class for digits
var numAlpha = new Regex("(?<Alpha>[\p{L} _]*)(?<Numeric>\d*)");
Further reading
For some regex basics you can see
my blog post What absolutely every Programmer should know about regular expressions
tutorial on regular-expressions.info (a very good source on regular expressions)
Upvotes: 3
Reputation: 912
Not sure if that's what you ask but - if you have 1 whitespace or underscore:
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)[ _]{1}(?<Numeric>[0-9]*)");
If you have many:
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)[ _]*(?<Numeric>[0-9]*)");
Upvotes: 0