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();
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With