带有固定字符串和一些用连字符分隔的变量的Javascript正则表达式
Javascript regex with fixed string and some variable separated by hyphen
我想测试类似的url:
/mobile/cars/volkswagen-vento-cars
我想为任何遵循下一个模式的url返回true
:
/mobile/cars/[Company]-[CarName]-cars
[Company]
可以是a-z
或A-Z
中的任何名称[CarName]
也可以由a-z
或A-Z
中的任何字符组成
有人能帮我写一个正则表达式来匹配上面的模式吗?
我的尝试是
/mobile'/cars'/[a-zA-Z]-[a-zA-Z]-cars/.test(text)
但没有成功。
测试用例
/mobile/cars/volkswagen-vento-cars : Valid,
/mobile/cars/volkswagen-vento-cars/ : Valid,
/mobile/cars/volkswagen-vento-cars-in-city: Invalid
现在它应该与您的URL 匹配
'/mobile'/cars'/['w]+-['w]+-cars'/?.*$
在此处测试
测试用例:
var str = "/mobile/cars/volkswagen-vento-cars-in-city";
var patt = new RegExp("'/mobile'/cars'/[A-z'-]+-cars('/[^-]*)?$");
var res = patt.test(str);
if( res ) {
//true
}else {
//false
}
使用此正则表达式:
/^[/]mobile[/]cars[/][a-z]+-[a-z]+-cars(?=[/]|$)/i
Legenda
/ # Start regex js delimiter
^ # Match the beginning of the string
[/] # Match a literal slash '/' (i prefer this form over ''/')
mobile # Match the literal string 'mobile'
[/] # as above
cars # Match the literal string 'cars'
[/] # as above
(?: # Start non capturing group
[a-z]+- # One or more of lowercase letters followed by a literal dash '-'
# (the ignorecase flag 'i' makes it matches also uppercase ones)
){2} # Exactly two of the above, equivalent to [a-z]+-[a-z]+-
cars # Match the literal string 'cars'
(?=[/]|$) # Lookahead, cars HAVE to be followed by a slash '/'
# or by the end of the string '$'
/i # ignore case flag [a-z] match also [A-Z]
实时演示
var re = /^[/]mobile[/]cars[/](?:[a-z]+-){2}cars(?=[/]|$)/i;
var tests = ['/mobile/cars/volkswagen-vento-cars-whatever-dash-something/slash/a-beautiful-car.html','/mobile/cars/volkswagen-vento-cars/whatever-dash-something/slash/a-beautiful-car.html','/mobile/cars/volkswagen-vento-cars/whatever','/mobile/cars/volkswagen-vento-cars-in-city','/mobile/cars/volkswagen-vento-cars','/mobile/cars/volkswagen-vento-cars/'];
var m;
while(t = tests.pop()) {
document.getElementById("r").innerHTML += '"' + t + '"<br/>';
document.getElementById("r").innerHTML += 'Valid URL prefix? ' + ( (t.match(re)) ? '<font color="green">YES</font>' : '<font color="red">NO</font>') + '<br/><br/>';
}
<div id="r"/>
相关文章:
- 如何将单词(包括单词)与连字符匹配
- 删除图形和数字之间的连字符(-)符号
- JQuery根据连字符前的首字母对列表进行排序
- 如何替换javascript字符串中的前三个连字符
- 带有连字符的 Jquery 表排序器编号
- Javascript将所有文本框值更改为连字符
- regex中连字符的这种用法有效吗
- 使用连字符引用对象的属性名称
- 用连字符分隔匹配值
- 跳过用户输入的文本字符串中的特殊字符,并在 Javascript 中的每个单词后添加连字符
- 为什么不'我的javascript函数允许点,但允许连字符
- 如何防止电子邮件地址的css自动连字符
- 如何仅替换第一个数字(用连字符分隔)
- 正则表达式表示用连字符分隔的浮点范围(用于年份和月份)
- 带有固定字符串和一些用连字符分隔的变量的Javascript正则表达式
- 在AngularJS中,当指令属性的作用域变量基于camelBase时,为什么它们需要用连字符分隔
- 逗号和空格分隔的数字和连字符分隔的字符串正则表达式
- 用连字符分隔的逻辑连接字符串
- 正则表达式检测仅用连字符分隔的任何数字
- 如何在使用lodash _.words时不分隔破折号/连字符