简体   繁体   中英

Retrieving specific characters from string separated by a delimiter

I want to retrieve characters separated by a specific delimiter.

Example :

Here, I want to access the string between the " " delimiters. But I want the 2nd set of characters between "".

abc"def"ghi"jklm // Output : ghi

"hello" yes "world" // output : world

How can I get that? I know we can use split. But sometimes the string might not start with " character.

Can anyone please help me with this?

string valueStr = "abc\"def\"ghi\"jklm";
var result = valueStr.Split('"')[2];
Console.WriteLine(result);

https://dotnetfiddle.net/T3fMof

Obviously check for the array elements before accessing them

You can just find the first quote, and use your approach from there:

var firstQuote = str.IndexOf('"');

var startsWithQuote = str.Substring(firstQuote);

You can use regular expressions to match them:

        var test = "abc\"def\"ghi\"jklm";
        var test2 = "\"hello\" yes \"world\"";

        var match1 = Regex.Matches(test, ".+\"(.+)\"");
        var match2 = Regex.Matches(test2, ".+\"(.+)\"");

        Console.WriteLine("Match1: " + match1[0].Groups[1].Captures[0]);
        Console.WriteLine("Match2: " + match2[0].Groups[1].Captures[0]);
        // Match1: ghi
        // Match2: world

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