繁体   English   中英

如何使用正则表达式查找以下模式?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM