Reputation: 36601
I want to extract email id between < >
for example.
input string : "abc" <[email protected]>; "pqr" <[email protected]>;
output string : [email protected];[email protected]
Upvotes: 9
Views: 47158
Reputation: 391
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
Upvotes: 12
Reputation: 45096
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.
Upvotes: 3
Reputation: 8116
Could use the following regex and some linq.
var regex = new Regex(@"\<(.*?)\>");
var input= @"""abc"" <[email protected]>; ""pqr"" <[email protected]>";
var matches = regex.Matches(input);
var res = string.Join(";", matches.Cast<Match>().Select(x => x.Value.Replace("<","").Replace(">","")).ToArray());
The <> brackets get removed afterwards, you could also integrate it into Regex
I guess.
Upvotes: 0
Reputation: 116108
string input = @"""abc"" <[email protected]>; ""pqr"" <[email protected]>;";
var output = String.Join(";", Regex.Matches(input, @"\<(.+?)\>")
.Cast<Match>()
.Select(m => m.Groups[1].Value));
Upvotes: 7
Reputation: 11311
string str = "\"abc\" <[email protected]>; \"pqr\" <[email protected]>;";
string output = string.Empty;
while (str != string.Empty)
{
output += str.Substring(str.IndexOf("<") + 1, str.IndexOf(">") -1);
str = str.Substring(str.IndexOf(">") + 2, str.Length - str.IndexOf(">") - 2).Trim();
}
Upvotes: -2
Reputation: 20722
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.
Upvotes: 3