Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

503
Views
javascript regex to find multiple strings in a line preceded by a key:

How can I match all the strings, in any order, but only if preceded by certain key?

example I want to match article and legal no matter the order as long as they are preceded by tags:

---
author: Karen the Trollmaster
tags: noise, legal, irrelevant, article
keywords: pff, nobody, likes, "a Karen", "not this", article // < don't match this one
---

What I have so far is

(?<=(tags: ))(article)|(legal)

but this isn't working correctly.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I would do this in two steps, first isolate the tags: line, then use match() to find all keywords with an alternation regex.

var input = `---
author: Karen the Trollmaster
tags: noise, legal, irrelevant, article
keywords: pff, nobody, likes, "a Karen", "not this", article // < don't match this one
---`;
var keywords = ["article", "legal"];
var regexp = new RegExp("\\b(" + keywords.join("|") + ")\\b", "g");
var matches = input.match(/\btags:.*?(?=\n|$)/)[0].match(regexp);
console.log(matches);

about 4 years ago · Juan Pablo Isaza Report

0

You can write the pattern as:

(?<=tags: .*)\b(?:article|legal)\b

The pattern matches:

  • (?<= Positive lookbehind, assert to the left from the current position
    • tags: .* Match tags: and 0+ times any
  • ) Close lookbehind
  • \b(?:article|legal)\b Match either article or legal between word boundaries

Regex demo

Note that you can omit the capture groups for a match only

const regex = /(?<=tags: .*)\b(?:article|legal)\b/gm;
const str = `---
author: Karen the Trollmaster
tags: noise, legal, irrelevant, article
keywords: pff, nobody, likes, "a Karen", "not this", article // < don't match this one
---`;

console.log(str.match(regex));

If both words should be present, you can make use of lookarounds to match either of the words and assert the other word to be present on the left or the right side

(?<=tags: .*)(?:\blegal\b(?=.*\barticle\b)|\barticle\b(?=.*\blegal\b)|(?<=.*\barticle\b.*)\blegal\b|(?<=.*\blegal\b.*)\barticle\b)

Regex demo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!