简体   繁体   中英

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?

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.

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.

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)

Why not run the regex on the substring?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM