Reputation: 40032
If I have a string of data with numbers in it. This pattern is not consistent. I would like to extract all numbers from the string and only a character that is defined as allowed. I thought RegEx might be the easiest way of doing this. Could you provide a regex patter that may do this as I think regex is voodoo and only regex medicine men know how it works
eg/
"Q1W2EE3R45T" = "12345"
"WWED456J" = "456"
"ABC123" = "123"
"N123" = "N123" //N is an allowed character
UPDATE: Here is my code:
var data = Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
data = data.Select(x => Regex.Replace(x, "??????", String.Empty)).ToArray();
Upvotes: 15
Views: 16763
Reputation: 101604
String numbersOnly = Regex.Replace(str, @"[^\d]", String.Empty);
Using Regex.Replace(string,string,string)
static method.
To allow N
you can change the pattern to [^\dN]
. If you're looking for n
as well you can either apply RegexOptions.IgnoreCase
or change the class to [^\dnN]
Upvotes: 23
Reputation: 123632
No need to use regexes! Just look through the characters and ask each of them whether they are digits.
s.Where(Char.IsDigit)
Or if you need it as a string
new String(s.Where(Char.IsDigit).ToArray())
EDIT Apparently you also need 'N'
:
new String(s.Where(c => Char.IsDigit(c) || c == 'N').ToArray())
EDIT EDIT Example:
var data = Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
data = data.Select(s =>
new String(s.Where(c => Char.IsDigit || c == 'N').ToArray())
).ToArray();
That's kinda horrible -- nested lambdas -- so you might be better off using the regex for clarity.
Upvotes: 4
Reputation: 13755
How about something along the lines of
String s = "";
for ( int i = 0; i < myString.length; ){
if ( Char.IsDigit( myString, i ) ){ s += myString.Chars[i]; }
}
Upvotes: 1