简体   繁体   中英

Javascript Complex RegEx with variables

I am using this tool to build a 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] :

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:

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

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.

Update your jsBin with these variable declarations, it should work now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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