Home > Backend Development > C++ > How Can C# Regex Split Strings with Commas Inside Quotes?

How Can C# Regex Split Strings with Commas Inside Quotes?

Mary-Kate Olsen
Release: 2025-01-07 21:10:45
Original
147 people have browsed it

How Can C# Regex Split Strings with Commas Inside Quotes?

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

The goal is to split this string into three different parts:

  1. 'ABCDEFG'
  2. 123542
  3. 'XYZ 99,9'

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

Usage:

<code class="language-csharp">var result = Regex.Split(sampleString, ",(?=(?:[^']*'[^']*')*[^']*$)");</code>
Copy after login

Explanation:

  • "," matches any comma in the string.
  • (?=( starts a lookahead assertion.
  • (?:[^']'[^']')* matches any number of sequences of non-single quote characters, followed by a single quote character.
  • [^']* matches any number of non-single quote characters.
  • $ matches the end of the string.

Output:

The output of the result array is as follows:

<code>{"'ABCDEFG'", "123542", "'XYZ 99,9'"}</code>
Copy after login

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!

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