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

Javascript regex with fixed string and some variable separated by hyphen

本文关键字:分隔 连字符 变量 正则表达式 Javascript 字符串      更新时间:2023-09-26

我想测试类似的url:

/mobile/cars/volkswagen-vento-cars

我想为任何遵循下一个模式的url返回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 

现在它应该与您的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"/>