Regular expression to match a word or its prefix

后端 未结 4 794
盖世英雄少女心
盖世英雄少女心 2020-12-07 13:33

I want to match a regular expression on a whole word.

In the following example I am trying to match s or season but what I have matches

4条回答
  •  一个人的身影
    2020-12-07 14:06

    I test examples in js. Simplest solution - just add word u need inside / /:

    var reg = /cat/;
    reg.test('some cat here');//1 test
    true // result
    reg.test('acatb');//2 test
    true // result
    

    Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

    var reg = /\bcat\b/
    reg.test('acatb');//1 test 
    false // result
    reg.test('have cat here');//2 test
    true // result
    

    We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

    var matchResult = /\bcat\b/.exec("good cat good");
    console.log(matchResult.index); // 5
    

    If we need get all matched words in string/sentence/text, we can use g modifier (global match):

    "cat good cat good cat".match(/\bcat\b/g).length
    // 3 
    

    Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

    "bad dog bad".match(/\bcat|dog\b/g).length
    // 1
    

提交回复
热议问题