简体   繁体   English

为什么我的RegEx可以在PHP中工作,而不能在JavaScript中工作?

[英]Why is my RegEx working in PHP but not in JavaScript?

I can't get those RegEx pattern to work with JavaScript (in PHP they work): 我无法使那些RegEx模式与JavaScript一起使用(在PHP中它们可以工作):

/^[^\/home\/]/
/^\/home\/$/
/^\/home\/.+\/.+$/

I want to allow input like this: 我想允许这样的输入:

/home/username

What I don't want is: 我不想要的是:

/home/
/username
/home/username/info

Here is my code: 这是我的代码:

var regex1 = /^[^\/home\/]/;
var regex2 = /^\/home\/$/;
var regex3 = /^\/home\/.+\/.+$/;
if( regex1.test(homedir)
|| regex2.test(homedir)
|| regex3.test(homedir) ) { ... }

I have no errors in the console. 我在控制台中没有错误。

Could someone explain to me why it is not working in JavaScript? 有人可以向我解释为什么它不能在JavaScript中工作吗?

EDIT 编辑

I changed it to /^\\/home\\/[A-Za-z0-9]+$/ and now it's working: 我将其更改为/^\\/home\\/[A-Za-z0-9]+$/ ,现在可以正常使用了:

var rgx = /^\/home\/[A-Za-z0-9]+$/;
if( !rgx.test(homedir) ) { ... }

Remove the string start Regex parameter ^ 删除字符串开始Regex参数^

You will now have: \\/home\\/.+\\/.+$ 您现在将拥有: \\/home\\/.+\\/.+$

Example built here showing validation: Regex Home URL example 此处显示验证示例Regex主页URL示例

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

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