开发者

Regular expression for matching incomplete tags in the form $tagname$

开发者 https://www.devze.com 2023-01-15 07:10 出处:网络
I have a small templating system in javascrip, where the user can put tags in the form $tagname开发者_Python百科$. I can match all tags with the patter: /\\$\\w+\\$/.

I have a small templating system in javascrip, where the user can put tags in the form $tagname开发者_Python百科$. 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?


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.


\$\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: [^$].


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消