tags:

views:

73

answers:

3

Hi All,

I am looking after fixing a bug and there I find this expression:-

 directoryPath = Regex.Replace(directoryPath, "[^\\w\\.@-]", "");

but as a result of the expression all the high ascii characters in directory path are messed up, I am not good at regex and dont know about it but for now I have to fix the issue .

Can someone please explain me what this regular expression does?

A: 

It appears to be removing the first character from directoryPath that is not a word character (digits, letters, underscores), period, @ symbol or hyphen.

I've just tried it with C:\Scratch\Filename.txt, and it leaves me with CScratchFilename.txt.

Andy Shellam
not first but any and \w is not a "whitespace"
zerkms
@Andy, why does it mess up the high ascii characters?
Ranjeet
@Ranjeet: because Andy doesn't know what is \w. which actually means "word character". so [^\\w] equals to "non-word characters"
zerkms
It's removing all characters that is not a word character (digit, letter, underscore), period, @ symbol or hyphen. Can you elaborate on what it should be doing?
Andy Shellam
@zerkms - ah, I always get that mixed up! I think it's \s I was thinking of.
Andy Shellam
+1  A: 

It seems that you are having encoding issues. For example, Regex could have treated your string as ASCII when it really was stored as UTF-8.

badp
wrong. it's not utf issue. it just because \\w doesn't contain chars he expected. i bet because locale specified wrongly.
zerkms
+3  A: 

It replaces anything that is NOT

  1. word character OR
  2. . (dot) OR
  3. @ OR
  4. - (dash)

    with nothing.

INPUT

    var directoryPath = @"C.@-(:\abc123/\def.foo";

OUTPUT

    [email protected]

Modified code to replace with space and corresponding output

    var directoryPath = @"  @.-abcd efghi(^-^)/\:[email protected]   [email protected]";

    Console.WriteLine(directoryPath);

   //note change here
   //second argument to Replace function is chanted from "" to " "

    directoryPath = Regex.Replace(directoryPath, "[^\\w\\.@-]", " ");

    Console.WriteLine(directoryPath);

Output:

  @.-abcd efghi(^-^)/\:[email protected]   [email protected]
  @.-abcd efghi  -     [email protected]   [email protected]
TheMachineCharmer