Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.?

So far I have tried /\(([^)\)]+)\)/ however it returns everything with parentheses. I only want the page numbers with parentheses.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can match the 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 )

\(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]))
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading