简体   繁体   English

如何使用“&”或“?”进行正则表达式调用? 作为第一个角色

[英]How to make a regex call with a '&' or '?' as first character

I am trying to make a regex call with the following string: 我正在尝试使用以下字符串进行正则表达式调用:

if ((/&timeout=true|?scn=header/i).test(url))

... and the statement continues. ...,声明继续。 I am receiving this error in the console: 我在控制台中收到此错误:

Uncaught SyntaxError: Invalid regular expression: /&timeout=true|?scn=header/ : Nothing to repeat 未捕获的SyntaxError:无效的正则表达式: /&timeout=true|?scn=header/ :无需重复

How do I properly make this statement? 我该如何正确地发表此声明?

您必须转义问号字符,因为它是正则表达式运算符:

if ((/&timeout=true|\?scn=header/i).test(url))

The problem is that ? 问题是? has a special meaning of repeat zero or one times , hence the error. 具有重复0或1次的特殊含义,因此是错误。 Just escape it: 逃脱它:

/&timeout=true|\?scn=header/

Try /(&timeout=true|\\?scn=header)/i 尝试/(&timeout=true|\\?scn=header)/i

? is a special character in regex so you need to escape it 是正则表达式中的特殊字符,因此您需要对其进行转义

Demo: http://www.regexr.com/3bqlu 演示: http : //www.regexr.com/3bqlu

Try this: 尝试这个:

/[&\\?]timeout=true|[&\\?]scn=header/

It matches both 两者都匹配

http://example.com/file.html?scn=header&timeout=true
http://example.com/file.html?timeout=true&scn=header

because we don't know which parameter comes first 因为我们不知道哪个参数先出现

这似乎有效

/\\&timeout=true|\\/?scn=header/i

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

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