正则表达式如何匹配这样的路径

匹配www.xxx.com/profile
或者www.xxx.com/profile/
不匹配www.xxx.com/profile/sdfsdf

阅读 9.8k
5 个回答
var reg = /^www\.[a-z0-9]+\.com\/[a-z0-9]+\/?$/;

// 之所以用[a-z0-9]+而不是\w+是排除如果字符串的如果存在下划线的匹配影响

图片描述

var str1 = 'www.xxx.com/profile';
var str2 = 'www.xxx.com/profile/';
var str3 = 'www.xxx.com/profile/sdfsdf';

console.log(reg.test(str1))  // true
console.log(reg.test(str2))  // true
console.log(reg.test(str3))  // false

希望能帮到你, 正则分析在线地址 https://regexper.com/

感兴趣的话也可以去看我写的正则入门文章

/^www.xxx.com\/profile\/?$/.test(str)
/^www\.\w+\.com\/\w+\/?$/
/^www.xxx.com\/profile(?=\/*$)/g.test(url)

/^www.xxx.com\/profile\/?$/

之前把第三种也匹配上了,实际你是不需要的,所以使用$收个尾就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题