Reputation: 629
I can't find the magic formula to get my regex working in Javascript. let's say I have:
const branchnames = [
{ name:'WICO-29', key:1 },
{ name:'WICO-9', key:2 },
{ name:'wico-2', key:3 },
{ name:'wiCo-2: description', key:4 },
{ name:'WiCO-2 example ', key:5 },
{ name:'WiCO-2-dosomething', key:6 },
{ name:'wiCO-2, great', key:7 },
];
I would like to recover every names excepts for the first two. Hence I am looking for a regex looking for "wico-2" (not case sensitive), followed either by nothing or a non alphanumerical character. Following attempts didn't work...
const reg = new RegExp(/wico-2[ ,:-]?$/, "i"); // miss: 4,5,6,7
const reg = new RegExp(/wico-2\W/, "i"); // miss: 3
const reg = new RegExp(/wico-2\W?/, "i"); // wrong:1
const reg = new RegExp(/wico-2\W?$/, "i"); // only 3
branchnames.forEach( element => {
console.log ( element.name.match(reg));
});
any help ? thanks !
Upvotes: 0
Views: 855
Reputation: 13232
You could do this:
/wico-2(([ ,:-]+|$).*$)/
Here is a link to regex tester:Regex
Upvotes: 0
Reputation: 2691
You can use regex as /wico-2(?!\d)/gi
const branchnames = [
{ name:'WICO-29', key:1 },
{ name:'WICO-9', key:2 },
{ name:'wico-2', key:3 },
{ name:'wiCo-2: description', key:4 },
{ name:'WiCO-2 example ', key:5 },
{ name:'WiCO-2-dosomething', key:6 },
{ name:'wiCO-2, great', key:7 },
];
const reg = new RegExp(/wico-2(?!\d)/, "gi");
branchnames.forEach( element => {
if(element.name.match(reg)){
console.log (element);
}
});
Upvotes: 1
Reputation: 26191
One might do as follows;
var branchnames = [
{ name:'WICO-29', key:1 },
{ name:'WICO-9', key:2 },
{ name:'wico-2hello', key:3 },
{ name:'wico-2', key:3 },
{ name:'wiCo-2: description', key:4 },
{ name:'WiCO-2 example ', key:5 },
{ name:'WiCO-2-dosomething', key:6 },
{ name:'wiCO-2, great', key:7 },
];
branchnames.forEach(bn => /wico-2(?=[^\dA-Za-z]|$)/i.test(bn.name) && console.log(bn.name));
Upvotes: 0
Reputation: 29451
I would use /wico-2(?:\D+|$)/
to do this:
const branchnames = [
{ name:'WICO-29', key:1 },
{ name:'WICO-9', key:2 },
{ name:'wico-2', key:3 },
{ name:'wiCo-2: description', key:4 },
{ name:'WiCO-2 example ', key:5 },
{ name:'WiCO-2-dosomething', key:6 },
{ name:'wiCO-2, great', key:7 },
];
const reg = new RegExp(/wico-2(?:\D+|$)/, "i");
branchnames.forEach( element => {
console.log ( element.name.match(reg));
});
Explanation of (?:\D+|$)
:
(?:\D+|$)
\D+
: matches any character that's not a digit (equal to [^0-9])+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) $
: asserts position at the end of the stringUpvotes: 1