Nan0
Nan0

Reputation: 61

Can't get the value of regex Match in a string

I have a form with a Listbox, in this Listbox i have datas from a .xml file.

When i select an input i get the value of this input in a var string with :

string s = lstCust.SelectedItem.ToString();

It gives me : "John Doe, [email protected] phone:00336598745"

Now i would like to get only the mail address so I'm trying it with this Regex :

@"([A-Za-z0-9._ % -] +@[A-Za-z0-9.-] +\.[a-zA-Z]{2,4})*"

With this method :

string mail = Regex.Match(s, @"([A-Za-z0-9._ % -] +@[A-Za-z0-9.-] +\.[a-zA-Z]{2,4})*").Value;

I'm sure my Regex works because a

Regex.Match(s, @"([A-Za-z0-9._ % -] +@[A-Za-z0-9.-] +\.[a-zA-Z]{2,4})*").Success.ToString();

gives me a true.

But the value of my var mail is always equals to "" (empty).

Any idea on what am i doing wrong ?

Thx

Upvotes: 2

Views: 169

Answers (3)

hawkstrider
hawkstrider

Reputation: 4341

You have spaces in your regex pattern that are preventing it from matching. Remove the spaces and the * at the end

string mail = Regex.Match(s, @"([A-Za-z0-9._ % -]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4})").Value;

Regex Storm Example

Upvotes: 4

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try the below Regex.

([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)

It will give you the email [email protected] from the give string John Doe, [email protected] phone:00336598745

Regex Demo

Upvotes: 1

ikkentim
ikkentim

Reputation: 1648

Your expression does not actually match. You have a * (0 or more occurrences) after your capture group. Because the expression doesn't actually match, it finds 0 occurrences of the expression in the capture group, but because of the * this is allowed, thus the matching succeeds.

If there is only one email address in the string you're matching against. remove the * at the end and try to find out why the regex isn't actually working.

Upvotes: 0

Related Questions