tags:

views:

52

answers:

1
+1  Q: 

c# regex replace

Consider a string like this,

type="xxx.yyy.zzz, xxx.yyy, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null"

I read a resx file and would like to replace all occurrences of the above string with String.Empty no matter what the Version is, but the version format will remain the same and the rest of the string does not change. I tried a few things but I'm in a bit of a crunch; and would really appreciate any help on this. Thanks.

+1  A: 
type="xxx\.yyy\.zzz, xxx\.yyy, Version=\d+\.\d+\.\d+\.\d+, Culture=neutral, PublicKeyToken=null"
  • \d stands for a digit; \d+ matches one or more digits.
  • . is a special character and needs to be escaped as \.

As a c# regex string, it'd look like:

pattern = "type=\"xxx\\.yyy\\.zzz, xxx\\.yyy, Version=\\d+\\.\\d+\\.\\d+\\.\\d+, Culture=neutral, PublicKeyToken=null\"";
Amarghosh
Hhm, what if there is a extra space or if version is only specified to x.x.x or if culture is not neutral. I know it is not your Regex there is faulty, but rather the question which lacks some information.
lasseespeholt
@lasseespeholt OP said _rest of the string does not change_ and I relied on that.
Amarghosh
Yes, I know :) Again, I know your regex is not faulty. But will a extra space qualify for "a change"? <- question for Bala R
lasseespeholt
@lasseespeholt there won't be an extra space.
Bala R
@Bala and does this regex work for you?
Amarghosh
I'm now struggling with the Unrecognized escape sequence error. Will update once I get it to work.
Bala R
oops - make all those \ to \\ - one for java, one for regex. See my update @Bala
Amarghosh
I don't understand. why do I need the java regex string ?in c# i tried replaciont \ with \\; that compiles but does not work.
Bala R
@Bala C# or java, you need to escape backslashes in a string.
Amarghosh
ok that worked. Thanks.
Bala R