Extracting string between two characters?

34,076

Solution 1

string input = @"""abc"" <[email protected]>; ""pqr"" <[email protected]>;";
var output = String.Join(";", Regex.Matches(input, @"\<(.+?)\>")
                                    .Cast<Match>()
                                    .Select(m => m.Groups[1].Value));

Solution 2

Without regex, you can use this:

public static string GetStringBetweenCharacters(string input, char charFrom, char charTo)
    {
        int posFrom = input.IndexOf(charFrom);
        if (posFrom != -1) //if found char
        {
            int posTo = input.IndexOf(charTo, posFrom + 1);
            if (posTo != -1) //if found char
            {
                return input.Substring(posFrom + 1, posTo - posFrom - 1);
            }
        }

        return string.Empty;
    }

And then:

GetStringBetweenCharacters("\"abc\" <[email protected]>;", '<', '>')

you will get

[email protected]

Solution 3

Tested

string input = "\"abc\" <[email protected]>; \"pqr\" <[email protected]>;";
matchedValuesConcatenated = string.Join(";", 
                                Regex.Matches(input, @"(?<=<)([^>]+)(?=>)")
                                .Cast<Match>()
                                .Select(m => m.Value));

(?<=<) is a non capturing look behind so < is part of the search but not included in the output

The capturing group is anything not > one or more times

Can also use non capturing groups @"(?:<)([^>]+)(?:>)"

The answer from LB +1 is also correct. I just did not realize it was correct until I wrote an answer myself.

Solution 4

Use the String.IndexOf(char, int) method to search for < starting at a given index in the string (e.g. the last index that you found a > character at, i.e. at the end of the previous e-mail address - or 0 when looking for the first address).

Write a loop that repeats for as long as you find another < character, and everytime you find a < character, look for the next > character. Use the String.Substring(int, int) method to extract the e-mail address whose start and end position is then known to you.

Share:
34,076
Vishwanath Dalvi
Author by

Vishwanath Dalvi

SOreadytohelp about me box is kept "", intentionally.

Updated on July 09, 2022

Comments