medium
medium

Reputation: 4236

Regex - find specific string with email address within

I am trying to parse out some email header information using a regular expression. My strings will have a format that looks something like this:

String one = "The quick brown fox jumps over the fence From: First Email <[email protected]>";
String two = "Some filler text From: <[email protected]>";

I need to create a regex that will get find strings that will return "From: First Email " from the first string and "From: " from from the second string

so far this is my pattern but it is not working:

 Pattern p = Pattern.compile("From: [@[\\w]+.[\\w]{2,3}]");

Currently it is only returning "From: F" and null respectively for the two strings.

Upvotes: 0

Views: 300

Answers (3)

DevinBM
DevinBM

Reputation: 91

why not write your regex a little more specifically?

I.E. "[<]{1}[a-z1-9]+@{1}[a-z1-9]+[.]{1}[a-z]{3}[>]{1}"

that should find a match for any e-mail address that's within < and > and doesn't contain any capital letters.

to add the "FROM:" on there. how about add "FROM:[a-z1-9A-Z ]+" to the beginning. I.E.: "FROM:[a-z1-9A-Z ]+[<]{1}[a-z1-9]+@{1}[a-z1-9]+[.]{1}[a-z]{3}[>]{1}"

Upvotes: 0

stema
stema

Reputation: 92976

How about this:

From: [^<]*

See it here on Regexr

My solution: Look for "From: " and then capture everything that is not a "<"

The pattern you posted has nothing to do with the problem you have, has it?

With the square brackets are you creating character classes that matches the characters inside the class.

[@[\\w]+.[\\w]{2,3}]
1111111  22222

The 1 marks your first character class it includes @,[ and word characters \w, you match this once or more (because of the +), then one character, then the next class consisting only of \w this 2 or 3 times. At last an unmatched closing square bracket ==> The compiler should have fallen about this one

Upvotes: 0

morja
morja

Reputation: 8550

Try:

"From: [^<]*"

this matches anything up to the opening bracket <

Upvotes: 1

Related Questions