简体   繁体   English

匹配单词的正则表达式

[英]regular expression for matching a word

I want to get the variable names in javascript which define a string for that I have wrote a regular expression我想获取 javascript 中的变量名,它定义了一个字符串,我已经写了一个正则表达式

var x = "sdfsfsdf";

((\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)

The problem with this expression is when I am using RegExp.$2 I should get the variable name as x as we consider the above code.这个表达式的问题是,当我使用RegExp.$2时,我应该将变量名称设为x ,因为我们考虑上面的代码。 It works fine with some expression but if there is code like它可以很好地处理某些表达式,但如果有类似的代码

function(a) {var b = document.createElement("script");}

then the result is function(a){var b .那么结果是function(a){var b

Please help me change my regular expression so it works in both cases.请帮助我更改我的正则表达式,以便它在两种情况下都适用。

NOTE: javascript variables can also be declared without var ie x = "sdfsfsf";注意:javascript 变量也可以不用var来声明,即x = "sdfsfsf";

If your strings won't be too crazy, you can try this:如果你的琴弦不会太疯狂,你可以试试这个:

/[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi

Tests:测试:

> var r = /[a-z_$][a-z0-9$_]*\s*=\s*.*?(;|$)/gi;
  undefined
> 'var x = "sdfsfsdf";'.match(r);
  ["x = "sdfsfsdf";"]
> 'function(a) {var b = document.createElement("script");}'.match(r);
  ["b = document.createElement("script");"]
/(^|;|{)\s*(var\s+)?(\S+)\s*=\s*['"][^'"]*['"]\s*(}|;|$)/i

(^|;|{)          at the beginning, after a semicolon or the bracket
\s*              0-n whitespace characters
(var\s+)?        could be followed by "var" with at least one whitespace
(\S+)            at least one none whitespace character
\s*=\s*          equal sign with possibly surrounded whitespaces
['"][^'"]*['"]   a 'string'
\s*(}|;|$)       have to end with the bracket or a semicolon or the end of the variable has been reached

Also see this example .另请参阅此示例

Try this regex: ([^\w]?(\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)试试这个正则表达式: ([^\w]?(\w.*?)(\s*=\s*)(['"]*)(.+?)(['"]*)\1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM