Looping through an array of assorted strings, I want to push into another array the strings that are separated by 3 or 4 hyphens
addon-4-website-m2maddon-4-website-comp-m2m
but not strings separated by 3 or 4 hyphens ending with annual:
addon-4-website-annualaddon-4-website-com-annual
What is the regex for filtering them?
CodePudding user response:
It is easier to use split and endsWith than a regular expression.
let parts = str.split('-');
if (parts.length >= 4 && parts.length <= 5 && !str.endsWith('annual')) {
// add to result
}
CodePudding user response:
I would express the regex as:
^\w (?:-\w ){2,3}-(?!annual$)\w $
This pattern says to match:
^from the start of the string\wa leading (first) component(?:-\w ){2,3}followed by 2 or 3 middle components-followed by hyphen(?!annual$)assert that last component does NOT end in "annual"\wthen match any other component$end of the string
Here is a working demo.
Here is how you may use this pattern in JavaScript:
if (/^\w (?:-\w ){2,3}-(?!annual$)\w $/.test("addon-4-website-m2m")) {
console.log("MATCH");
}
CodePudding user response:
You can use a negative lookahead:
^(\w -){3,4}(?!annual)\w $
^start of the string(\w -){3,4}3 or 4 words followed by an hyphen(?!annual)not followed by this word\wlast word$end of the string
