3

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

2
  • 2
    Have you tried anything yet? Post some code of what you've attempted so far. Commented Apr 10, 2012 at 5:25
  • Yes, I tried it, and it works. Commented Apr 10, 2012 at 16:22

2 Answers 2

6
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 .

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Jay. This solution works! It gets me motivated to learn more about Regular Expression.
0

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

3 Comments

This is a valid solution, but I disagree with your last comment. Your solution would break more readily than a good regex solution.
yes, I know about that, RegEx will work in most general cases, but if input string will always look like this - OP can consider using this, much simpler (and faster) solution. Anyway, obwiously correct answer to OP's question is Jay's answer - it makes heavy use of RegEx to replace only correct commas
As you mention, this solution should work, however, sometimes, the input string may / may not have extra spaces and the quotion marks could be single quotes. I didn't make it clear in my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.