RegEx for replacing all characters apart from numb

2020-07-03 04:03发布

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();

标签: c# .net regex
3条回答
▲ chillily
2楼-- · 2020-07-03 04:31

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.

查看更多
地球回转人心会变
3楼-- · 2020-07-03 04:39
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]

查看更多
疯言疯语
4楼-- · 2020-07-03 04:45

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]; }
}
查看更多
登录 后发表回答