简体   繁体   English

Simple Nodejs Regex:从两个字符串之间提取文本

[英]Simple Nodejs Regex: Extract text from between two strings

I'm trying to extract the Vine ID from the following URL: 我正在尝试从以下URL中提取Vine ID:

https://vine.co/v/Mipm1LMKVqJ/embed

I'm using this regex: 我正在使用这个正则表达式:

/v/(.*)/

and testing it here: http://regexpal.com/ 并在此处测试: http//regexpal.com/

...but it's matching the V and closing "/". ...但它匹配V并关闭“/”。 How can I just get "Mipm1LMKVqJ", and what would be the cleanest way to do this in Node? 我怎样才能得到“Mipm1LMKVqJ”,在Node中这样做最干净的方法是什么?

You need to reference the first match group in order to print the match result only. 您需要引用第一个匹配组才能打印匹配结果。

var re = new RegExp('/v/(.*)/');
var r  = 'https://vine.co/v/Mipm1LMKVqJ/embed'.match(re);
if (r)
    console.log(r[1]); //=> "Mipm1LMKVqJ"

Note: If the url often change, I recommend using *? 注意:如果网址经常更改,我建议使用*? to prevent greediness in your match. 防止你的比赛贪婪。

Although from the following url, maybe consider splitting. 虽然从以下网址,可能会考虑拆分。

var r = 'https://vine.co/v/Mipm1LMKVqJ/embed'.split('/')[4]
console.log(r); //=> "Mipm1LMKVqJ"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM