javascript javascript未终止字符类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14639339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:11:25  来源:igfitidea点击:

javascript unterminated character class

javascriptregex

提问by davej

var badCode = "\(INST1,\[0,";
var regex = new RegExp(badCode, "igm");

gets "unterminated character class" error.

得到“未终止的字符类”错误。

How to fix?

怎么修?

TIA

TIA

trying suggestions from responders to this post, please see the following screen prints (you might have to right-click on images and open in new tab to make legible): note values of new_bad_thing (equiv of badCode above)

尝试响应者对此帖子的建议,请查看以下屏幕打印(您可能需要右键单击图像并在新选项卡中打开以使其清晰可见):注意 new_bad_thing 的值(相当于上面的 badCode)

and here is the screen print when I hit the run button (please note the error message):

这是我点击运行按钮时的屏幕打印(请注意错误消息):

enter image description here

在此处输入图片说明

回答by Ofer Zelig

Put another backslash at badCode:

将另一个反斜杠放在badCode

var badCode = "\(INST1,\[0,";
var regex = new RegExp(badCode, "igm");

since you need one to escape (inside the regex itself (signal it that it's a literal parentheis) and one escape for javascript.

因为你需要一个(在正则表达式内部转义(表明它是一个文字括号)和一个用于 javascript 的转义。

回答by Ry-

No, it gets "unterminated parenthetical", because you've forgotten to escape the backslash. Why not use a regular expression literal?

不,它会变成“未终止的括号”,因为您忘记了转义反斜杠。为什么不使用正则表达式文字?

var regex = /\(INST1,\[0,/igm;