Bichvan Nguyen
Bichvan Nguyen

Reputation: 4129

Replace a character inside a string using C# Regex

I would like to know how to replace , characters inside array brackets [] with another character, say .. The string expression I have is below:

Attributes["412324 - PENNDOT I-95", "Category"].Value, Attributes["412324 - PENNDOT I-95", "Category"].Code

The expected output should be:

Attributes["412324 - PENNDOT I-95". "Category"].Value, Attributes["412324 - PENNDOT I-95". "Category"].Code

Upvotes: 3

Views: 2677

Answers (2)

Jay
Jay

Reputation: 57959

var regex = new Regex(@"(?<=\[[^\[\]]*),(?=[^\[\]]*\])");
return regex.Replace(<your sample string>, ".");

Within the regex pattern, to the left of the , is a positive lookbehind zero-width assertion that means there must be a [ and then zero or more characters that are neither [ nor ] leading up to the comma.

After the comma, a positive lookahead zero-width assertion that means there can be zero or more characters that are neither [ nor ] then there must be a closing ].

Zero-width assertions mean that the pattern must precede or follow the matched text, but are not part of the match. Since we are only matching the , our replacement is just the .

Upvotes: 6

Soul Reaver
Soul Reaver

Reputation: 2092

if it's always in this sheme, then faster would be String.Replace:

string sin = "Attributes["412324 - PENNDOT I-95", "Category"].Value, Attributes["412324 - PENNDOT I-95", "Category"].Code";
string sout = sin.Replace("\", \"","\". \"");

you can do the same with RegEx, but it would be slower and still it can break if the input string changes it's structure

Upvotes: 0

Related Questions