Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a character inside a string using C# Regex

Tags:

string

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

like image 589
Bichvan Nguyen Avatar asked May 18 '26 11:05

Bichvan Nguyen


1 Answers

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 .

like image 176
Jay Avatar answered May 19 '26 23:05

Jay