-1

I am trying to extract characters from a string. I want [a-z or A-Z or 0-9 or . or _] all other characters should be trimmed from the string.

I have a regular expression that can replace characters but I want other way around, I want a regular expression or any other method that allows only [a-z or A-Z or 0-9 or . or _] and remove all other characters.

Ian
  • 30,182
  • 19
  • 69
  • 107
Ali
  • 1,015
  • 14
  • 40
  • What was the problem with it then ? You can do it easily with regex ? what actually is the problem you faced ? – Code Cooker May 09 '17 at 05:15
  • What is the difference in Replacing characters or matching when using RegEx? – sachin May 09 '17 at 05:15
  • Does `Regex.Replace(text, "[^a-zA-Z0-9 _]", "")` work for you? – Enigmativity May 09 '17 at 05:16
  • Regex.Replace(text, "[^a-zA-Z0-9 _]", "") is replacing a-zA-Z0-9 _ with empty string and returning me characters which I don't want. I want other way around, I want only a-zA-Z0-9 _ and all other characters should be removed. – Ali May 09 '17 at 05:23
  • 1
    @Ali - You should try this code. Running `Regex.Replace("g%4 D-u!!u_e", "[^a-zA-Z0-9 _]", "")` returns `"g4 Duu_e"`. Isn't that what you want? – Enigmativity May 09 '17 at 05:24
  • @Ali - the `^` after the `[` says "not the following characters". – Enigmativity May 09 '17 at 05:26

2 Answers2

0

Try this simple function. This will just keep the correct characters.

    private string ClearUp(string inData) {
        var reg = new Regex("[^A-Za-z0-9._]");

        return reg.Replace(inData, string.Empty);
    }
MrApnea
  • 1,776
  • 1
  • 9
  • 17
0

Use the RegEx pattern [^\w.] to extract only a-z, A-Z, 0-9, _ or .

var cleanedString = Regex.Replace("yourstring", @"[^\w.]", string.Empty);

Here is the explanation:

  • \w represents a-z, A-Z, 0-9 or _
  • The . after \w would allow for literal '.'
  • The ^ at start means everything except what follows
  • RegEx.Replace would Replace any occurrence of unwanted characters (specified by pattern in second parameter) from supplied input (first parameter) with empty string (specified by the last parameter)
sachin
  • 2,341
  • 12
  • 24