tags:

views:

126

answers:

3

Howdy,

I'd like to return string between two characters, @ and dot (.).

I tried to use regex but cannot find it working.

(@(.*?).)

Anybody?

+6  A: 

Try this regular expression:

@([^.]*)\.

The expression [^.]* will match any number of any character other than the dot. And the plain dot needs to be escaped as it’s a special character.

Gumbo
+2  A: 

Your regular expression almost works, you just forgot to escape the period. Also, in PHP you need delimiters:

'/@(.*?)\./s'

The s is the DOTALL modifier.

Here's a complete example of how you could use it in PHP:

$s = '[email protected]';
$matches = array();
$t = preg_match('/@(.*?)\./s', $s, $matches);
print_r($matches[1]);

Output:

bar
Mark Byers
Sorry, I didn't notice that he was using multiline strings. Updated answer.
Mark Byers
andreas didn't say he was working with strings with line breaks, I just mentioned that if he were, the proposed solution wouldn't work. And now it does, of course.
Bart Kiers
Ah, yes I see now. I'm wondering if he is trying to parse emails... just a guess though.
Mark Byers
I try to get email address domain. @Mark Byers, your example shoots me with "Unknown modifier @". When adding \ before @ got blank page. Damn, hate regex :-)
Johannes
Nevermind, I think I'm to tired :( Thanks Mark, your answer does the trick. Thanks!
Johannes
andreas, how will you know on which DOT to split? What if the address is `[email protected]` or `[email protected]`?
Bart Kiers
Also @ is a valid character in the first part of the address as long as it is escaped or in quotes, e.g. "firstname@lastname"@example.com - see http://www.apps.ietf.org/rfc/rfc3696.html page 6. You should consider using a standards compliant email parser rather than trying to roll your own.
Mark Byers
+1  A: 

If you're learning regex, you may want to analyse those too:

@\K[^.]++(?=\.)

(?<=@)[^.]++(?=\.)

Both these regular expressions use possessive quantifiers (++). Use them whenever you can, to prevent needless backtracking. Also, by using lookaround constructions (or \K), we can match the part between the @ and the . in $matches[0].

Geert