JavaScript正则表达式,在哪里使用转义字符? [英] JavaScript Regex, where to use escape characters?

查看:127
本文介绍了JavaScript正则表达式,在哪里使用转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式允许使用以下字符:字母数字,空格,' - ','_','&','()'和'/'



<这是表达式

  [\s\ / \)\(\w&  - ] 

我已经在各种在线测试人员测试过,知道它的工作原理,我不能让它正常工作代码我得到sysntax错误任何我尝试..任何建议?

  var programProductRegex = new RegExp([\s\\ \\ / \)\(\w&  - )); 


解决方案

您可以使用正则表达式语法:

  var programProductRegex = / [\s\ / \ )\(\w&  - )/; 

您使用正斜杠来分隔正则表达式



如果您使用RegExp对象构造函数,则需要传递一个字符串,因为反斜杠是JavaScript中的特殊转义字符串ngs,它们也是正则表达式中的转义字符,您需要使用两个反斜杠来在字符串中执行正则表达式转义。然后使用字符串的等效代码将是:

  var programProductRegex = new RegExp([\\s\\\ \\ / \\)\\(\\w&安培;  - ]); 

原始正则表达式中的所有反斜杠需要在字符串中进行转义才能正确解释作为反斜杠。



当然第一个选项更好。当您从某个地方获取一个字符串并希望使其成为一个正则表达式时,该构造函数很有用。

  var programProductRegex = new正则表达式(userInput); 


The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'

this is the expression

[\s\/\)\(\w&-]

I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?

var programProductRegex = new RegExp([\s\/\)\(\w&-]);

解决方案

You can use the regular expression syntax:

var programProductRegex = /[\s\/\)\(\w&-]/;

You use forward slashes to delimit the regex pattern.

If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:

var programProductRegex  = new RegExp("[\\s\\/\\)\\(\\w&-]");

All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.

Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.

var programProductRegex  = new RegExp(userInput);

这篇关于JavaScript正则表达式,在哪里使用转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆