-1

It look and sound very simply - regex that working in other parts of code just fine, here it's not working - always return "N/A". Can't get what's wrong with that?

private string FindEmail(string description)
        {
            try
            {
                const string pattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
                Match m = Regex.Match(description, pattern);
                string emailaddr = m.Success ? m.Value : "N/A";
                return emailaddr;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error in Link Data Repository {0} in Parse Links {1}", ex.Message, ex.StackTrace);
                throw new Exception(ex.Message);
            }
        }

Description string look like that:

Phase 1 plots in Al Furjan
75% paid
25% to pay in November 2014

6,544 sq ft plot with BUA of 4,908 sq ft 

Call Nicoleta 055-5573564 or email: nicoleta.mihoc@group7properties.com

Al Furjan is located in a convenient location just off the Emirates Road and the Dubai Investment Park Road within the Jebel Ali community Zone. This 560 Hectare Mega development is consisted of family town houses & villas of 3 to 6 bedrooms, and will offer a much needed boost for family villas within the commuter zone of Dubai.

Inspired by a historic Arabic phrase from Dubai's proud past, Al Furjan symbolizes a collection of homes or a small village. 
A "fareej" (a single village) represented a way of life to its residents, one that created a community of extended family and friends, rather than merely neighbors.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
  • 1
    Don't use `^` and `$`. As your code currently stands, it will only match the email if the entire description consists of one email address. – ProgramFOX Feb 15 '15 at 20:12
  • have you considered a google search for `RegEx Email validatin` ? - [Email validation using regex](http://stackoverflow.com/questions/5342375/c-sharp-regex-email-validation) – MethodMan Feb 15 '15 at 20:13
  • how the string `description` looks like? – Avinash Raj Feb 15 '15 at 20:13

2 Answers2

1

Since the e-mailaddress is surrounded by other text, you will want to allow text before and after the regex pattern. This can be achieved as follows:

string pattern = @"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+";

So, the difference is that this pattern does not include the ^ and $.

T.S.
  • 1,242
  • 13
  • 22
0

You need to remove the anchors from your regex since the email address is not the only one present on a line. Anchor ^ asserts that we are at the start of a line and $ asserts that we are at the end of a line.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274