Back then I found PHP's own PCRE syntax reference quite good: http://uk.php.net/manual/en/reference.pcre.pattern.syntax.php
Let's talk about your expression. It's quite a bit more verbose than necessary; I'm going to simplify it while we go through this.
A rather simpler way of looking at what you're trying to match: "find a {
, then any number of letters or underscores, then a }
". A regular expression for that is (in PHP's string-y syntax): '/\{[a-z_]+\}/'
This will match all of your examples but also some wilder ones like {__a_b}
. If that's not an option, we can go with a somewhat more complex description: "find a {
, then a bunch of letters, then (as often as possible) an underscore followed by a bunch of letters, then a }
". In a regular expression: /\{([a-z]+(_[a-z]+)*\}/
This second one maybe needs a bit more explanation. Since we want to repeat the thing that matches _foo
segments, we need to put it in parentheses. Then we say: try finding this as often as possible, but it's also okay if you don't find it at all (that's the meaning of *
).
So now that we have something to compare your attempt to, let's have a look at what caused your problems:
- Your expression matches any characters inside the
{}
, including }
and {
and a whole bunch of other things. In other words, {abcde{_fgh}
would be accepted by your regex, as would {abcde} fg_h {ijkl}
.
- You've got a mandatory
_
in there, right after the first .*
. The (_){1}
(which means exactly the same as _
) says: whatever happens, explode if this ain't here! Clearly you don't actually want that, because it'll never match {email}
.
Here's a complete description in plain language of what your regex matches:
- Match a
{
.
- Match a
_
.
- Match absolutely anything as long as you can match all the remaining rules right after that anything.
- Match a
_
.
- Match a single letter.
- Instead of that
_
and the single letter, absolutely anything is okay, too.
- Match a
}
.
This is probably pretty far from what you wanted. Don't worry, though. Regular expressions take a while to get used to. I think it's very helpful if you think of it in terms of instructions, i.e. when building a regular expression, try to build it in your head as a "find this, then find that", etc. Then figure out the right syntax to achieve exactly that.
This is hard mainly because not all instructions you might come up with in your head easily translate into a piece of a regular expression... but that's where experience comes in. I promise you that you'll have it down in no time at all... if you are fairly methodical about making your regular expressions at first.
Good luck! :)