Home > Backend Development > C++ > How Can I Split a Comma-Separated String in C# While Ignoring Commas Within Quotes?

How Can I Split a Comma-Separated String in C# While Ignoring Commas Within Quotes?

Linda Hamilton
Release: 2025-01-07 21:29:41
Original
885 people have browsed it

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>
Copy after login

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>
Copy after login

The splitString array will then contain:

  • splitString[0] = 'ABCDEFG'
  • splitString[1] = 123542
  • splitString[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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template