views:

39

answers:

3

I have a small templating system in javascrip, where the user can put tags in the form $tagname$. I can match all tags with the patter: /\$\w+\$/.

Also, I want to match incomplete tags specifically (it would start with $ and finish with a word boundary that is not $). I can't use /\$\w+\b/ because $ is also a word boundary (so it will also match correct tags). I tried with this but it does not work: /\$\w+[^\$]/.

It matches the incomplete tag in this string "word $tag any word", but it also matches this "word $tag$ any word".

What is the correct ending for that regular expresion?

+2  A: 
\$\w+\b\$?

Your try \$\w+[^\$] does not work because [^\$] must match something, while \$? matches optionally. Well, and because you did not define where the word boundary is.

Besides, escaping the $ in a character class is not strictly necessary, this is the same thing: [^$].

Tomalak
A: 

So, if $ is treated as a word boundary, why not just do: \$\w+\b? Otherwise, just use \$\w+[\$\b], I guess, even though that would be redundant.

mway
`\$\w+[\$\b]` won't work; in a character class, `\b` matches a backspace, not a word boundary.
Alan Moore
+2  A: 

If you want to match incomplete tags specifically, you can use a negative lookahead:

\$\w+(?![$\w])

But it's probably more efficient to use Tomalak's regex and do a separate check to see if it ends with $. Or capture the (optional) ending $ like this:

\$\w+\b(\$?)

If group #1 contains an empty string, it's an incomplete tag.

Alan Moore
I was not clear enough that I wanted to match incomplete tags specifically, so this did the trick.
NachoCual