简体   繁体   English

Javascript复杂的RegEx与变量

[英]Javascript Complex RegEx with variables

I am using this tool to build a regex http://www.gethifi.com/tools/regex 我正在使用此工具构建一个正则表达式http://www.gethifi.com/tools/regex

I found that the one below works for me if, for example, I am looking to match $aazz[AB] : 我发现下面的那个对我$aazz[AB] ,例如,我想要匹配$aazz[AB]

var regex = /[\+\=\-\*\^\\]\$aazz\[AB\]/g; 

I have read the other posts on the RegEx constructor in Javascript but cannot manage to make the following work: 我已经阅读了Javascript中RegEx构造函数的其他帖子,但无法完成以下工作:

var preToken = "[\+\=\-\*\^\\]";    
var toFind = "\$aazz\[AB\]";

var stringToReplace = "/" + preToken + toFind + "/";

var regex = new RegExp(stringToReplace, "g");

Here is the jsbin http://jsbin.com/ifeday/3/edit 这是jsbin http://jsbin.com/ifeday/3/edit

Thanks 谢谢

When creating regular expressions from strings, you need to escape your backslashes twice. 从字符串创建正则表达式时,需要两次转义反斜杠。

\ becomes \\
\\ becomes \\\\

So, you can try (in a character class not everything needs escaping): 所以,你可以尝试(在角色类中不是所有东西都需要转义):

var preToken = "[+=\\-*^\\\\]"; 
var toFind = "azz\\[A\\]";

Also, the string source for your regular expression does not need to be bound by / s, but I see in your jsBin that you've already corrected that. 此外,正则表达式的字符串源不需要被/ s绑定,但我在你的jsBin中看到你已经纠正了它。

Update your jsBin with these variable declarations, it should work now. 使用这些变量声明更新您的jsBin,现在应该可以正常工作。

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

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