javascript 简单的 Nodejs 正则表达式:从两个字符串之间提取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25965439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Nodejs Regex: Extract text from between two strings
提问by opticon
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 "/". How can I just get "Mipm1LMKVqJ", and what would be the cleanest way to do this in Node?
...但它匹配 V 并关闭“/”。我怎样才能得到“Mipm1LMKVqJ”,在 Node 中最干净的方法是什么?
回答by hwnd
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.
注意:如果 url 经常变化,我建议使用它*?
来防止你的匹配中的贪婪。
Although from the following url, maybe consider splitting.
虽然从下面的网址,也许可以考虑拆分。
var r = 'https://vine.co/v/Mipm1LMKVqJ/embed'.split('/')[4]
console.log(r); //=> "Mipm1LMKVqJ"