C# regular expression string splitting: commas outside quotation marks
Handling strings containing embedded commas can be challenging using traditional comma-based splitting methods. This article demonstrates a solution using C# and regular expressions to split a string containing commas that may be surrounded by quotes.
Problem Statement:
Consider the following string representing a SQL code snippet:
<code>('ABCDEFG', 123542, 'XYZ 99,9')</code>
The goal is to split this string into three different parts:
The challenge arises because the comma in the third parameter ("XYZ 99,9") should not be considered a separator.
Regular expression solution:
To solve this problem, we can use a regular expression that only matches a comma if it is preceded by an even number of single quotes. This mode ensures that commas within quotes are not split.
<code>",(?=(?:[^']*'[^']*')*[^']*$)"</code>
Usage:
<code class="language-csharp">var result = Regex.Split(sampleString, ",(?=(?:[^']*'[^']*')*[^']*$)");</code>
Explanation:
Output:
The output of the result array is as follows:
<code>{"'ABCDEFG'", "123542", "'XYZ 99,9'"}</code>
This demonstrates successfully splitting a string based on commas outside quotes while keeping the quoted arguments intact.
The above is the detailed content of How Can C# Regex Split Strings with Commas Inside Quotes?. For more information, please follow other related articles on the PHP Chinese website!