簡體   English   中英

Javascript中的RegEx match()不會按預期生成結果

[英]RegEx match() in Javascript does not produce result as expected

我無法弄清楚為什么Javascript中的正則表達式無法正常工作。

模式如下:

\[(.+)\]\((.+)\)

嘗試按以下格式匹配文本:

[Learn more](https://www.example.com)

 const text = 'Lorem ipsum etc [Learn more](https://www.google.com), and produce costly [test link](https://www.google.com). [another test link](https://www.google.com).' const regex = /\\[(.+)\\]\\((.+)\\)/ const found = text.match(regex) console.log(found) 

我期待找到的值如下:

[
    "[Learn more](https://www.google.com)",
    "[test link](https://www.google.com)",
    "[another test link](https://www.google.com)"
]

但價值似乎如下:

[
    "[Learn more](https://www.google.com), and produce costly [test link](https://www.google.com). [another test link](https://www.google.com)",
    "Learn more](https://www.google.com), and produce costly [test link](https://www.google.com). [another test link",
    "https://www.google.com"
]

我已經嘗試了/ ig標志,但這似乎不起作用。 我正在嘗試不同的應用程序(RegExRX)並獲得預期的結果,但在Javascript中,我無法得到它產生相同的結果。

+量詞是貪婪的,並且會盡可能多地“吃掉”源字符串。 你可以使用.+? 代替:

const regex = /\[(.+?)\]\((.+?)\)/

更好的是,而不是. 匹配“不是”:

const regex = /\[([^\]]+)\]\(([^)]+)\)/

明確排除邊界字符無論如何都可以表現得更好。

TL; DR :正則表達式\\[(.+?)\\]\\((.+?)\\)應該這樣做。

原始模式不起作用的原因是因為默認情況下+量詞是“貪婪的” - 它會嘗試匹配盡可能多的字符。 因此, .+表示“盡可能多的除了新行字符之外任何東西 ”。 你已經可以知道右括號符合定義了。

為了使它正常工作,你必須說“盡可能多的東西,直到第一個結束括號”。 要做到這一點,你應該用.+ by [^\\]]+[^\\)]+代替第二組),或者只是通過附加它來使上述量詞不那么貪心? ,它將兩個捕獲組都變成(.+?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM