1

i have a ploblem. im genereting a small scipt for text matches cont and ordering match counts. click to see jsfiddle live example

my example scripts :

var testtext1 = "apple banana and kiwi pineapple juice";
var testtext2 = "need apple banana pineapple milkshake";
var testtext3 = "apple pineapple lower prices";
var testtext4 = "only apple banana kiwi pineapple lovers";
var testtext5 = "kiwi pineapple apple banana sales";

alert(testtext1.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //3 matches
alert(testtext2.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext3.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext4.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext5.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //3 matches

text1= only 3 matches why ? watch regex

apple banana kiwi OR apple banana OR apple OR banana OR kivi

apple banana kiwi NO match 0

apple banana YES match 1

appple YES match 2

banana YES match 3

kiwi YES match 4

okay why return 3 matches not 4 matches ?? and other examples ?

see matchs this pic ?

1 Answer 1

1

Have a look at below demo

Live DEMO

surround it by word boundary otherwise pineapple will be matched by apple

\b(apple banana kiwi|apple banana|apple|banana|kiwi)\b

Matches

apple banana and kiwi pineapple juice        2
need apple banana pineapple milkshake        1
apple pineapple lower prices                 1
only apple banana kiwi pineapple lovers      1
kiwi pineapple apple banana sales            2

EDIT

If you change the order then the result will be something different

\b(apple|banana|apple banana kiwi|apple banana|kiwi)\b

Live DEMO

apple banana and kiwi pineapple juice        3
Sign up to request clarification or add additional context in comments.

3 Comments

I'm sorry I do not understand the logic of this match. Please wait a moment I'll add a picture to tell.
Thank you. After matching a word once again understood that match together.
Keep short words first in the group. \b(kiwi|apple|banana|apple banana|apple banana kiwi)\b but that condition will never be caught because apple is already captured hence there is no chance for apple banana and apple banana kiwi hence there is no use of extra words. Keep largest(bigger) words first in the group to match it first. Rest depends on your choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.