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

79
Views
javascript regex to match a combination of and/or expression

I want to match a combination of and/or expression and match only sentences in between for example

test1 test2 and test2 or test4 test5

I want to get matches test1 test2, test2, test4 test5

I tried this regex https://regex101.com/r/FFLtg6/1 but it doesn't work :

(.+)(((and|or)\s+)?)+

Update : I need a regex expression because it is part of a bigger regex.

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

0

Here's what you're looking for:

const txt = "lorem ipsum and dolor and sit or amet consecteturand elit";

console.log(txt.split(/ and | or /));

about 4 years ago · Juan Pablo Isaza Report

0

  1. You can use this regexp:

const text = "test1 test2 and test2 or test4 test5";
const regexp = /(?<=^|and |or ).*?(?= and| or|$)/g;

console.log(text.match(regexp));

P.S. But keep in mind that positive lookbehind feature is not supported in all browsers

  1. You can use this regexp which will not ignore all empty spaces around need parts:

const text = "   test1 test2    and    test2    or    test4 test5   ";
const regexp = /\s*(?!and|or)\b.*?(?=and|or|$)/g;

console.log(text.match(regexp));

  1. You can use this regexp which will ignore all empty spaces around need parts:

const text = "    test1 test2    and    test2    or    test4 test5     ";
const regexp = /(?!and|or|\s)\b.*?(?=\s*(and|or|$))/g;

console.log(text.match(regexp));

about 4 years ago · Juan Pablo Isaza Report

0

I would probably just do the obvious:

const rxWords = /\S+/g;
const rxConnectors = /^(and|or)$/i;
const nonConnector = w => ! rxConnectors.test(w) ;

function getInterestingWords( s ) {
  const corpus  = s ?? '' ;
  const matches = corpus.match( rxWords ) ;
  const words   = matches.filter( nonConnector ) ;

  return words;
}

Given that, executing

const text = 'test1 test2 and test2 or test4 test5f' ;
const interestingWords = getInterestingWords(text);

sets interestingWords to the expected

[ 'test1', 'test2', 'test2', 'test4', 'test5' ]
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!