Thursday, April 28, 2011

Replacing numbers in strings with C#

I'd thought i do a regex replace

Regex r = new Regex("[0-9]"); 
return r.Replace(sz, "#");

on a file named aa514a3a.4s5 . It works exactly as i expect. It replaces all the numbers including the numbers in the ext. How do i make it NOT replace the numbers in the ext. I tried numerous regex strings but i am beginning to think that its a all or nothing pattern so i cant do this? do i need to separate the ext from the string or can i use regex?

From stackoverflow
  • Yes, I thing you'd be better off separating the extension.

    If you are sure there is always a 3-character extension at the end of your string, the easiest, most readable/maintainable solution would be to only perform the replace on

    yourString.Substring(0,YourString.Length-4)
    

    ..and then append

    yourString.Substring(YourString.Length-4, 4)
    
    acidzombie24 : I voted for the other guy bc of the better solution (i love how you both use very few words) and bc i dont like the hardcoded 4 in your example ;P. .split all the way :D
    Tiberiu Ana : Split isn't that great either -- you must assume that there are no '.' characters anywhere else in the string, and a filename (most likely that's what this is) can have them all over the place. It all depends on the exact details of the problem.
    ck : System.IO.Path.GetFilename may be better in this instance, but see Kamiel Wanrooij's solution for how to do it in Regex.
  • I don't think you can do that with a single regular expression.

    Probably best to split the original string into base and extension; do the replace on the base; then join them back up.

  • Why not run the regex on the substring?

    String filename = "aa514a3a.4s5";
    String nameonly = filename.Substring(0,filename.Length-4);
    
  • This one does it for me:

    (?<!\.[0-9a-z]*)[0-9]

    This does a negative lookbehind (the string must not occur before the matched string) on a period, followed by zero or more alphanumeric characters. This ensures only numbers are matched that are not in your extension.

    Obviously, the [0-9a-z] must be replaced by which characters you expect in your extension.

    acidzombie24 : awesome. This is the first time i change my accepted answer.
    Kamiel Wanrooij : glad I could help!

0 comments:

Post a Comment