开发者

Simple regex: how do I say: "it's okay to have an " s " or " es " or " 's " at the end of the word, match those too."?

开发者 https://www.devze.com 2023-03-07 07:42 出处:网络
I\'m using Jquery(don\'t know if that\'s relevant), here\'s the regex: var re = new RegExp(\'\\\\b\' + a_filter + \'\\\\b\');

I'm using Jquery(don't know if that's relevant), here's the regex:

var re = new RegExp('\\b' + a_filter + '\\b');

So it matches whole words in the variabe a_filter which has a bunch of words in it. Right now it will match 'wrench', but not 'wrenches'. It will match 'chair', but not 'chairs', it will match "john" but not "john's". I've been trying but I can't figure it out.

Can someone please help me adjust my regex above to allow for these at the end of the word?

s es 's are what I want to allow at the end of a word match, so i don't have to include every single possible variation of each开发者_Go百科 word. I think that's all the word endings that there really are that someone would type, if you know more, it would be great to get help, THANKS!

EDIT: here's my jsfiddle, maybe I had a_filter mixed up with filter_tags, I think i'm doing it backwards, ugh. ???

http://jsfiddle.net/nicktheandroid/mMTsc/18/


I have a group of your endings after the filter concatenation, with ? to require 0 or 1 match.

var a_filter = "wrench";
var re = new RegExp('\\b' + a_filter + '(s|es|\'s)?\\b');

alert( re.test("wrench's") );

Example: http://jsfiddle.net/qctAG/ (alert() warning. you'll get 4 of them)


You want something that looks like this:

var re = new RegExp('\\b' + a_filter + '(s|es|\'s)?\\b');

Of course, that will not match all plurals (e.g. oxen, geese) and it will match words that don't exist (e.g. sheeps).


This works for me...assuming you have an array!

var a_filter = ["wrench","wrenches","wrench's"];

for(var i=0; i < a_filter.length; i++){
    var re = new RegExp('\^' + a_filter[i] + '\$');
    document.write(re.test("wrench's") + " " + a_filter[i] + "<br />");
}

Here is the fiddle: http://jsfiddle.net/XCARd/2/ Play with the re.test() to see it match.

0

精彩评论

暂无评论...
验证码 换一张
取 消