views:

531

answers:

4

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?

+1  A: 

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)
Tiberiu Ana
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
acidzombie24
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.
Tiberiu Ana
System.IO.Path.GetFilename may be better in this instance, but see Kamiel Wanrooij's solution for how to do it in Regex.
ck
+2  A: 

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.

Douglas Leeder
+1  A: 

Why not run the regex on the substring?

String filename = "aa514a3a.4s5";
String nameonly = filename.Substring(0,filename.Length-4);
Bailz
+3  A: 

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.

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