Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string between character using regex c# [duplicate]

Tags:

c#

regex

What should be the Regex expression to extract string between <> from the following string :

 "MyName"<[email protected]>

How do i only extract [email protected] in c# using regex ? I can extract MyName which is in-between "" using the expression : """([^""]*)""" but i find regex very confusing so can't seem to figure out how to extract the string in-between <> :(

like image 815
Christopher H. Avatar asked Mar 12 '18 15:03

Christopher H.


1 Answers

Here it is:

public static void Main(string[] args)
{
    string input = "<[email protected]>";
    Regex rx = new Regex(@"<(.*?)>");

    Console.WriteLine(rx.Match(input).Groups[1].Value);
}

This regex contains several parts: < and > symbols say that my text is between them
() - is group declaration, what we see here Groups[1]. Zero group would contain whole line with <> symbols
.* - any character with any length
? - non-greedy search, so if you have there "<[email protected]><asdasd>" it will still return correct value and not get result [email protected]><asdasd

Example

like image 70
Alexey Klipilin Avatar answered Sep 30 '22 05:09

Alexey Klipilin