2

if I'm doing something like that:

someString.Replace("abc","").Replace("def","").Replace(@"c:\Windows","")

How can I replace that with

Regex.Replace(someString," \\here I don't know what the pattern should be")

I've tried this:

Regex.Replace(someString, @"(?:abc|def|c:\Windows)")

but it didn't work

UPD...

The problem is when I pass the path like that

Regex.Replace(someString, @"(?:abc|def|"+aPath+")")
1
  • make sure all backslashes are escaped. \ should be \\ Commented Jul 18, 2012 at 20:12

2 Answers 2

6
`But it didnt work` doesn't say much helpfull!

Try this:

someString = Regex.Replace(someString, @"(?:abc|def|ghi|c:\\Windows)", "")

It did work when I tried it. I thinks the reason why your code doesn't work is because you forgot the replacement string and you have to escape the backslash in the path.

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

Comments

3

I'm assuming the thing that "didn't work" is your C:\windows replacement. You need

someString = Regex.Replace(someString, @"(?:abc|def|C:\\windows)","");

The problem is you need to escape your backslash. An unescaped backslash has meaning in regex. In particular, in this case, \W actually matches any non-alphanumeric character.

Edit to escape an any arbitrary string, you can use Regex.Escape(yourString);

1 Comment

what if I'm passing a path like this: Regex.Replace(someString, @"(?:abc|def|"+aPath+","")

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.