简体   繁体   English

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

[英]How can I use regex to find the following pattern?

I have an array of strings like so:我有一个这样的字符串数组:

["Author Name, (p. 123). (2019). Company.", "Author Name, (p. 321). (2021). Company."]

How can I return the page numbers that start with and contain the pattern (p. ?如何返回以模式开头并包含模式的(p. ?

So far I have tried /\(([^)\)]+)\)/ however it returns everything with parentheses.到目前为止,我已经尝试过/\(([^)\)]+)\)/但是它返回带括号的所有内容。 I only want the page numbers with parentheses.我只想要带括号的页码。

You can match the p.你可以匹配p. before the capture group and capture the numbers.在捕获组之前并捕获数字。 You don't have to escape the parenthesis in the character class, so you can remove \) and leave just )您不必转义字符 class 中的括号,因此您可以删除\)并仅保留)

\(p\.\s*([^)]+)\)

See a regex demo .查看正则表达式演示

 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])) });

I'd capture digits (you need (ps) ?), case-insensitive (what about (P.12) ?):我会捕获数字(你需要(ps) ?),不区分大小写(那么(P.12)呢?):

/\(p\.\s*(\d+)\)/ig

Code代码

 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, '')))

EXPLANATION解释

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
--------------------------------------------------------------------------------
  \)                       ')'

See regex proof .请参阅正则表达式证明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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