Javascript正则表达式避免X和Y之间的单词

时间:2017-08-10 18:18:57

标签: javascript regex web

我对regEx了解不多,我想我可以做一些类似下面的模式,是吗?

www.url.com/travels/(IwannaAvoidThis)/anotherImportantThing

如果不清楚:我想匹配travels//anotherImportantThing而不关心(IwannaAvoidThis)

有可能吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用正则表达式捕获组,然后通过索引进行访问。

var url = 'www.url.com/travels/(IwannaAvoidThis)/anotherImportantThing';

var result = url.match(/(travels\/).*(\/anotherImportantThing)/);
console.log(result);
console.log(result[1]);
console.log(result[2]);

答案 1 :(得分:0)

使用此模式^[^\/]+\/([^\/]+)|([^\/]+)$ Demo

你想要的是捕获组1和2

^               # Start of string/line
[^\/]           # Character not in [\/] Character Class
+               # (one or more)(greedy)
\/              # "/"
(               # Capturing Group (1)
  [^\/]         # Character not in [\/] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
|               # OR
(               # Capturing Group (2)
  [^\/]         # Character not in [\/] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (2)
$               # End of string/line