我有一個帶有一些鏈接的降價檔案。我嘗試使用相應的鏈接文本來獲取所有這些鏈接。它適用于簡單的鏈接,但我不知道如何將鏈接與影像鏈接相匹配。
如果我有一個像 的影像鏈接[](https://other-example.com)
,我想獲取兩個鏈接和兩個鏈接文本。
我想出了兩個正則運算式:
/\[([^\]!] )]\((https:\/\/[^\)] )\)/gi
/\[([^\[!] )](\(https:\/\/[^\)] \))/gi
let str = `# Title with Image [](https://other-example.com)
## Links
- [First](https://somesite.com/path/to-page) - voluptates explicabo debitis aspernatur dolor, qui dolores.
- [Second](https://example.io/this/is/page) - molestiae animi eius nisi quam quae quisquam beatae reiciendis.`
let regex1 = /\[([^\]!] )]\((https:\/\/[^\)] )\)/gi
let regex2 = /\[([^\[!] )](\(https:\/\/[^\)] \))/gi
let links1 = [...str.matchAll(regex1)].map((m) => ({ text: m[1], link: m[2] }))
let links2 = [...str.matchAll(regex2)].map((m) => ({ text: m[1], link: m[2] }))
console.log(links1)
console.log(links2)
預期結果是(順序無關緊要):
[
{
"text": "",
"link": "https://other-example.com"
},
{
"text": "alt text",
"link": "https://example.com/image.svg"
},
{
"text": "First",
"link": "https://somesite.com/path/to-page"
},
{
"text": "Second",
"link": "https://example.io/this/is/page"
}
]
regex101鏈接
uj5u.com熱心網友回復:
([^\]!] )
阻止您匹配
,因此我將其替換為(!\[. ?\]\(. ?\)|. ?)
首先查找的內容
,然后將其替換為包含在(方括號)alt text
中的文本。[]
/(?=\[(!\[. ?\]\(. ?\)|. ?)]\((https:\/\/[^\)] )\))/gi
請注意,對于交叉匹配,您應該將模式包裝到積極的前瞻中。另請參閱演示。
let str = `# Title with Image [](https://other-example.com)
## Links
- [First](https://somesite.com/path/to-page) - voluptates explicabo debitis aspernatur dolor, qui dolores.
- [Second](https://example.io/this/is/page) - molestiae animi eius nisi quam quae quisquam beatae reiciendis.`
let regex = /(?=\[(!\[. ?\]\(. ?\)|. ?)]\((https:\/\/[^\)] )\))/gi
let links = [...str.matchAll(regex)].map((m) => ({ text: m[1], link: m[2] }))
console.log(links)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533753.html
上一篇:正則運算式查找其中包含單詞的評論