user34537
user34537

Reputation:

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?

Upvotes: 2

Views: 5552

Answers (4)

Kamiel Wanrooij
Kamiel Wanrooij

Reputation: 12404

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.

Upvotes: 3

Bailz
Bailz

Reputation: 615

Why not run the regex on the substring?

String filename = "aa514a3a.4s5";
String nameonly = filename.Substring(0,filename.Length-4);

Upvotes: 1

Douglas Leeder
Douglas Leeder

Reputation: 53320

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.

Upvotes: 2

Tiberiu Ana
Tiberiu Ana

Reputation: 3653

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)

Upvotes: 1

Related Questions