简体   繁体   中英

C# Get string between two characters in a string

I have a string like below:

{{"textA","textB","textC"}}

And currently, I'm using below code to split them:

string stringIWantToSplit = "{{\"textA\",\"textB\",\"textC\"}}";
string[] result = stringIWantToSplit.Split(',');

And I can get the below result:

{{"textA"
"textB"
"textC"}}

After that, I can manually trim out the '{' and '}' to get the final result, but here is the problem:

If the string is like below:

   `{{"textA","textB,textD","textC"}}`

Then the result will be different from Expected result

Expected result:

  "textA" 
  "textB,textD"
  "textC"

Actual result:

{{"textA" "textB textD" "textC"}}

How can I get the string between two double quotes?


Updated:

Just now when I checked the data, I found that some of them contains decimals ie

{{"textA","textB","",0,9.384,"textC"}}

Currently, I'm trying to use Jenish Rabadiya's approach, and the regex I'm using is

(["'])(?:(?=(\\\\?))\\2.)*?\\1

but with this regex, the numbers aren't selected, how to modify it so that the numbers / decimal can be selected?

Try using regex like following.

Regex regex = new Regex(@"([""'])(?:(?=(\\?))\2.)*?\1");
foreach (var match in regex.Matches("{{\"textA\",\"textB\",\"textC\"}}"))
{
    Console.WriteLine(match);
}

Here is working dotnet fiddle => Link

Assuming your string will always look like your examples, you can use a simple regular expression to get your strings out:

string s = "{{\"textA\",\"textB,textD\",\"textC\"}}";

foreach (Match m in Regex.Matches(s, "\\\".*?\\\""))
{
    //do stuff
}

I think this will help you,

List<string> specialChars = new List<string>() {",", "{{","}}" };
string stringIWantToSplit = "{{\"textA\",\"textB,textD\",\"textC\"}}";
string[] result = stringIWantToSplit.Split(new char[] {'"'}, StringSplitOptions.RemoveEmptyEntries)
            .Where(text => !specialChars.Contains(text)).ToArray();

使用这个正则表达式很简单:

text = Regex.Replace(text, @"^[\s,]+|[\s,]+$", "");

I finally modified the regex to this:

(["'])(?:(?=(\\?))\2.)*?\1|(\d*\.?\d*)[^"' {},]

And this finally works:

Sample:

https://dotnetfiddle.net/vg4jUh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM