'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.
Solution 1:[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
- 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));
- 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));
Solution 2:[2]
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 /));
Solution 3:[3]
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' ]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ale917k |
| Solution 3 | Nicholas Carey |
