正则表达式 - 匹配变量以javascript中的$开头?

时间:2015-01-09 00:45:30

标签: javascript regex

我希望匹配所有变量,例如$bar, $foo,我直到现在才这样:

(\$)+[A-Za-z]

4 个答案:

答案 0 :(得分:1)

这应该匹配一些由[A-Za-z0-9_]组成但不以数字开头的常见有效变量。

/(\$(?!\d)\w+)/g

/ .. /g   // regular expression is put between two //, the g behind is flag for global
( .. )    // a capturing group, can be called using \1 or $1 depending on regex processor
\$        // escaped character `$`
(?!\d)    // negative lookahead - ensures that next character after $ isn't a match ->
    -> \d // matches one digit
\w+       // one or more "word characters". Matches the ASCII characters [A-Za-z0-9_]

注意:如果您要全局匹配所有变量名称,则不需要任何捕获组,因此只需使用/\$(?!\d)\w+/g

  

根据php.net,这是正确的正则表达式:\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

编辑:我刚刚注意到你根本没有匹配PHP变量,但你现在就明白了。 :)

为了好玩http://regex.alf.nu/

答案 1 :(得分:1)

就是这样:

/\$[\w_]+/g

如果你想检查变量不是以数字开头,只需通过负向前瞻检查。 (?![\ d])

/\$(?![\d])[\w_]+/g

/ g 以匹配所有。

答案 2 :(得分:0)

\$[A-Za-z]+\w*

解释:$在开头,一个或多个字母,后跟0个或更多有效变量字母(取决于语言)。

有关详细说明,请参阅https://www.regex101.com/r/cB1bM1/1

答案 3 :(得分:0)

您可能需要的正则表达式是:

\$\w+