Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for replacing all characters apart from numbers

Tags:

c#

.net

regex

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();
like image 325
Jon Avatar asked Mar 19 '12 16:03

Jon


People also ask

How do I remove all characters from a string except numbers?

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.

Can regex replace characters?

They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters. Replacement patterns are provided to overloads of the Regex.

How do you replace all occurrences of a regex pattern in a string?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string.

How do you replace all occurrences of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.


1 Answers

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]

like image 61
Brad Christie Avatar answered Oct 21 '22 19:10

Brad Christie