Home >Backend Development >C++ >How to Split Comma-Separated Strings with Embedded Commas Inside Quotes in C#?

How to Split Comma-Separated Strings with Embedded Commas Inside Quotes in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-07 21:21:40256browse

How to Split Comma-Separated Strings with Embedded Commas Inside Quotes in C#?

Use C# to split comma separated strings outside quotes

For parameter strings containing embedded commas outside quotes, you can use regular expression methods to split them exactly.

Question:

Split the string "('ABCDEFG', 123542, 'XYZ 99,9')" into its component parts, where the last argument contains a comma within quotes.

Solution:

Use regular expressions to identify commas outside quotes to achieve the desired split:

<code class="language-c#">",(?=(?:[^']*'[^']*')*[^']*$)"</code>

This regex pattern matches any comma that does not appear before or after an odd number of quotes.

Implementation:

The following code uses regular expressions to split a sample string:

<code class="language-c#">string samplestring = "('ABCDEFG', 123542, 'XYZ 99,9')";
string[] result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)");</code>

Output:

The resulting array will contain the individual components:

<code>['ABCDEFG', '123542', 'XYZ 99,9']</code>

The above is the detailed content of How to Split Comma-Separated Strings with Embedded Commas Inside Quotes in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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