1

I have a small Regex here where I am removing all the white spaces from within a file and replacing them with '-'.

I want to also replace other characters with '-' such as ',' and '_'.

How can I list these characters in my regex?

Regex r = new Regex(@"\s+");

string fileName = r.Replace(Files.Name, @"-");

2 Answers 2

4
Regex r = new Regex(@"[\s,_-]+");

string fileName = r.Replace(Files.Name, @"-");

Be aware that the - must be the first, the last or you'll need escaping.

Sign up to request clarification or add additional context in comments.

2 Comments

@FailedDev It was a pedantic with a :-) or a :-D... A pe :-D antic
Just saying :) no offense intended! :)
3
Regex r = new Regex(@"(\s|-|,|_)+");

2 Comments

Uh, but that's an inefficent way to do it. @xanatos' version is cleaner and faster.
I think it's more readable as you don't need to worry about ordering or escaping characters, but that's personal preference. I think we're way into micro-optimization to call this 'inefficient' though. Yes, it may be a few milli-seconds slower if you loop over it thousands of times. Does that matter ? If absolute fastest is needed, straight string replace for each of the various characters would be faster still. Readability would generally be more important IMO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.