[英]I need a regEx to match string
I have url like this我有这样的 url
let url = " https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226 "让 url = " https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226 "
I need to match the substring "/merchant/docs/1568875072010.jpg"我需要匹配 substring "/merchant/docs/1568875072010.jpg"
I have found regEx to find the base of the url, but since in this case the filname is in between and not the end, I could not write a regEx myself.我找到了 regEx 来找到 url 的基础,但由于在这种情况下 filname 介于两者之间而不是结尾,所以我自己无法编写 regEx。
But I found a way, which is not very efficient但是我找到了一种方法,效率不是很高
var pathArray = url.split('/');
var a = pathArray[6].split('?')
var fileName = '/' + pathArray[4] + '/' + pathArray[5] + '/' + a[0]
I would need fileName to be "/merchant/docs/1568875072010.jpg"我需要文件名是“/merchant/docs/1568875072010.jpg”
The following Regex matches the pattern:以下正则表达式匹配模式:
\/[^\/]+\/[^\/]+\/[^\/]+(?=\.)\.[^?]+
Example:例子:
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>
An explanation of the Regex:正则表达式的解释:
\/
- matches a literal /
\/
- 匹配文字/
[^\/]+
- matches anything other than a /
at least once [^\/]+
- 匹配除/
以外的任何内容至少一次(?=\.)
- a positive lookahead asserting that what immediately follows the current position in the string is a literal dot (?=\.)
- 肯定的前瞻断言紧跟在字符串中当前 position 之后的是文字点\.
- matches a literal dot - 匹配文字点
[^?]+
matches anything that's not a literal question mark [^?]+
匹配任何不是文字问号的内容
Although your question is confusing to me.虽然你的问题让我很困惑。 Confusion is between:
混淆介于:
1: if you want to match /merchant/docs/1568875072010.jpg
to be in url string
then use includes
method 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: If you want to extract that information from url string: 2:如果要从 url 字符串中提取该信息:
console.log(new URL(url).pathname.replace("/dev-radius-backend", ""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.