Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS中的RegExp负前瞻_Javascript_Regex - Fatal编程技术网

Javascript JS中的RegExp负前瞻

Javascript JS中的RegExp负前瞻,javascript,regex,Javascript,Regex,我正在尝试编写一个RegExp,它将匹配除了一个以外的站点的所有子域。我认为最好的方法是向前看,我想我已经很接近了 我将以amazon.com为例。test.amazon.com将是我想要避免的子域 到目前为止,我得到了这个: var regexp = new RegExp("https?://(?!test\.)([^/]+\.)?amazon\.com/.*") 然而,(!test.)似乎会破坏任何以“test”开头的子域。我的希望是,\.只在“test”之后有一段时间时才会强制RegEx

我正在尝试编写一个RegExp,它将匹配除了一个以外的站点的所有子域。我认为最好的方法是向前看,我想我已经很接近了

我将以amazon.com为例。test.amazon.com将是我想要避免的子域

到目前为止,我得到了这个:

var regexp = new RegExp("https?://(?!test\.)([^/]+\.)?amazon\.com/.*")
然而,(!test.)似乎会破坏任何以“test”开头的子域。我的希望是,
\.
只在“test”之后有一段时间时才会强制RegExp失败。事实似乎并非如此

var regexp = new RegExp("https?://(?!test\.)([^/]+\.)?amazon\.com/.*")

regexp.test("https://amazon.com/")
true //Passes Correctly

regexp.test("https://www.amazon.com/")
true //Passes Correctly

regexp.test("https://atest.amazon.com/")
true //Passes Correctly

regexp.test("https://test.amazon.com/")
false //Fails Correctly

regexp.test("https://tester.amazon.com/")
false //Fails Incorrectly
张贴正确答案:

https?://(?!test)([^.]+\\.)?amazon\\.com/

如果您的意思是
“\”
,请在双引号中使用
“\”
。当解释字符串文字时,斜杠会被删除,因此RegExp会为您的
“\。”
获取纯
”。对于你的
“\\”
,它将得到(正确的)
“\\”
,这将解决问题(我不确定它是否是惯用的js;也许应该首选其他形式的字符串/regexp文本)。@AntonKovalenko是正确的,如果你将斜杠改为:var regexp=new regexp(“https?:/(!test\\)([^/]+\。)?amazon\\\.com/*”)查看一个工作示例。我认为您正在寻找类似于
https?:/(?!test)([^.]+\\)?amazon\\.com/
的东西,它做到了!如果你们中有人提出答案,我将接受。谢谢