我希望匹配所有变量,例如$bar, $foo
,我直到现在才这样:
(\$)+[A-Za-z]
答案 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变量,但你现在就明白了。 :)
答案 1 :(得分:1)
就是这样:
/\$[\w_]+/g
如果你想检查变量不是以数字开头,只需通过负向前瞻检查。 (?![\ d])
/\$(?![\d])[\w_]+/g
/ g 以匹配所有。
答案 2 :(得分:0)
答案 3 :(得分:0)
您可能需要的正则表达式是:
\$\w+