Sen
Sen

Reputation: 145

regex for formatting words

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");

Upvotes: 2

Views: 118

Answers (2)

John Knoeller
John Knoeller

Reputation: 34148

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=")

Upvotes: 4

Joey
Joey

Reputation: 354506

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

Regex.Replace(inputString, "(?=Address2=|State=)", "&");

Upvotes: 3

Related Questions