我想测试与此类似的网址:
/mobile/cars/volkswagen-vento-cars
我想为下一个模式后面的任何网址返回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
答案 0 :(得分:1)
测试用例:
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
}
答案 1 :(得分:1)
答案 2 :(得分:0)
使用此正则表达式:
/^[/]mobile[/]cars[/][a-z]+-[a-z]+-cars(?=[/]|$)/i
<强>勒亘强>
/ # 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/>';
}
&#13;
<div id="r"/>
&#13;