带有固定字符串的Javascript正则表达式和用连字符分隔的一些变量

时间:2015-12-24 09:35:09

标签: javascript regex

我想测试与此类似的网址:

/mobile/cars/volkswagen-vento-cars

我想为下一个模式后面的任何网址返回true

/mobile/cars/[Company]-[CarName]-cars
  • [Company]可以是a-zA-Z
  • 中的任意名称
  • [CarName]也可以由a-zA-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 

3 个答案:

答案 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)

你应该匹配你的网址

\/mobile\/cars\/[\w]+-[\w]+-cars\/?.*$

Test Here

答案 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]

现场演示

&#13;
&#13;
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;
&#13;
&#13;