tags:

views:

66

answers:

2

how can I format below string

Address1=+1234+block+of+XYZ+Street+Address2=+Santa+Fe+Springs+State=+California

to string

Address1=+1234+block+of+XYZ+Street+&Address2=+Santa+Fe+Springs+&State=+California

The below regex doesnt work properly.could someone fix this?

string inputString = "Address1=+1234+block+of+XYZ+Street+Address2=+Santa+Fe+Springs+State=+California";
string outString = Regex.Replace(inputString,@"([\s])([a-zA-Z0-9]*)(=)","&$1");
+3  A: 

If all you want to do is prefix "Address2" and "State" by an ampersand:

Regex.Replace(inputString, "(?=Address2=|State=)", "&");
Joey
What if someone lives on State St.? Might be better to match `State=` for the second case.
jball
the only problem I have with this is sometime my inputs has address2.is there a w ay to escape case sesitivity?
Sen
@jball yes thats a valid scenario.
Sen
This is a clearer for the specific question, but it doesn't scale well if there are more keywords.
John Knoeller
+4  A: 

I think you want this

Regex.Replace(inputString,@"\+([a-zA-Z0-9]+)=","+&$1=")

Or this if you want to allow any character other than + & = in keywords.

Regex.Replace(inputString,@"\+([^+&=]+)=","+&$1=")
John Knoeller
@John, for this case `\+([^+%=]+)=` might be a better character set to match...
gnarf
@gnarf: + rather than * for sure, I'm less certain about allowing chars other than alpha and numbers as keywords. Might be better, might not. I'll make the + change
John Knoeller
John Knoeller
yeah, sry, aircoding ftw...
gnarf