[英]How to get the match for the following use cases with the regex pattern that i have?
[英]How can I use regex to find the following pattern?
我有一個這樣的字符串數組:
["Author Name, (p. 123). (2019). Company.", "Author Name, (p. 321). (2021). Company."]
如何返回以模式開頭並包含模式的(p.
?
到目前為止,我已經嘗試過/\(([^)\)]+)\)/
但是它返回帶括號的所有內容。 我只想要帶括號的頁碼。
你可以匹配p.
在捕獲組之前並捕獲數字。 您不必轉義字符 class 中的括號,因此您可以刪除\)
並僅保留)
\(p\.\s*([^)]+)\)
查看正則表達式演示。
const regex = /\(p\.\s*([^)]+)\)/g; [ "Author Name, (p. 123). (2019). Company.", "Author Name, (p. 321). (2021). Company." ].forEach(s => { Array.from(s.matchAll(regex), m => console.log(m[1])) });
我會捕獲數字(你需要(ps)
?),不區分大小寫(那么(P.12)
呢?):
/\(p\.\s*(\d+)\)/ig
代碼
const regex = /\(p\.\s*(\d+)\)/gi const string = "Author Name, (p. 123). (2019). Company." console.log(string.match(regex).map(x => x.replace(/\D+/g, '')))
解釋
NODE EXPLANATION
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
p 'p'
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\) ')'
請參閱正則表達式證明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.