我需要一个正则表达式来匹配字符串

时间:2019-10-04 12:49:32

标签: javascript regex

我有这样的网址

let url =“ https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226

我需要匹配子字符串“ /merchant/docs/1568875072010.jpg”

我已经找到regEx来查找url的基础,但是由于在这种情况下filname位于两者之间而不是结尾,因此我无法自己编写regEx。

但是我找到了一种方法,它不是很有效

var pathArray = url.split('/');
var a = pathArray[6].split('?')
var fileName = '/' + pathArray[4] + '/' + pathArray[5] + '/' + a[0]

我需要fileName为“ /merchant/docs/1568875072010.jpg”

2 个答案:

答案 0 :(得分:1)

以下正则表达式与模式匹配:
\/[^\/]+\/[^\/]+\/[^\/]+(?=\.)\.[^?]+

示例:

var url = 'https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226';
var match = url.match(/\/[^\/]+\/[^\/]+\/[^\/]+(?=\.)\.[^?]+/);
    
if (match) {
    console.log(match[0]); // "/merchant/docs/1568875072010.jpg"
    document.getElementById('result').innerText = match[0];
}
<span id="result"></span>

正则表达式的解释:
\/-匹配文字/
[^\/]+-至少匹配一次/以外的任何内容
(?=\.)-积极的前瞻性主张,紧随字符串当前位置之后的是文字点
\.-匹配文字点
[^?]+匹配所有非文字问号

答案 1 :(得分:0)

尽管您的问题让我感到困惑。混乱之间:

1::如果您想将/merchant/docs/1568875072010.jpg匹配到url string中,请使用includes方法

var url = "https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226";
if (str.includes("/merchant/docs/1568875072010.jpg")) {
   alert('file found in URL')
}

2 :如果您要从网址字符串中提取该信息,则:

console.log(new URL(url).pathname.replace("/dev-radius-backend", ""));