Home >Backend Development >C++ >How Can I Split a Comma-Separated String in C# While Ignoring Commas Within Quotes?
C# Regular Expression Splitting: Handling Commas in Quoted Strings
Standard C# comma-based string splitting fails when dealing with commas within quoted text. Regular expressions provide a robust solution.
Consider splitting the string "('ABCDEFG', 123542, 'XYZ 99,9')" into its three constituent parts: 'ABCDEFG', 123542, and 'XYZ 99,9'.
The following regular expression identifies commas outside quoted sections:
<code class="language-csharp">",(?=(?:[^']*'[^']*')*[^']*$)"</code>
This expression ensures that only commas not preceded by an even number of single quotes (indicating a closed quoted section) are used as split points.
Here's how to use it with Regex.Split
:
<code class="language-csharp">string inputString = "('ABCDEFG', 123542, 'XYZ 99,9')"; string[] splitString = Regex.Split(inputString, ",(?=(?:[^']*'[^']*')*[^']*$)");</code>
The splitString
array will then contain:
splitString[0]
= 'ABCDEFG'splitString[1]
= 123542splitString[2]
= 'XYZ 99,9'This regular expression approach accurately splits strings, preserving data integrity even when commas appear within quoted substrings.
The above is the detailed content of How Can I Split a Comma-Separated String in C# While Ignoring Commas Within Quotes?. For more information, please follow other related articles on the PHP Chinese website!