Regular expression to match a word or its prefix

后端 未结 4 793
盖世英雄少女心
盖世英雄少女心 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:15

    Square brackets are meant for character class, and you're actually trying to match any one of: s, |, s (again), e, a, s (again), o and n.

    Use parentheses instead for grouping:

    (s|season)
    

    or non-capturing group:

    (?:s|season)
    

    Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.

提交回复
热议问题