简体   繁体   中英

RegEx for replacing all characters apart from numbers

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();
String numbersOnly = Regex.Replace(str, @"[^\d]", String.Empty);

Using Regex.Replace(string,string,string) static method.

Sample

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]

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.

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]; }
}

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