Regex find word in the string

前端 未结 3 876
孤街浪徒
孤街浪徒 2020-12-28 14:16

In general terms I want to find in the string some substring but only if it is contained there.

I had expression :

^.*(\\bpass\\b)?.*$
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 14:28

    You're just missing a bit for it to work (plus that ? is at the wrong position).

    If you want to match the frist occurance: ^(.*?)(\bpass\b)(.*)$. If you want to match the last occurance: ^(.*)(\bpass\b)(.*?)$.

    This will result in 3 capture groups: Everything before, the exact match and everything following.

    . will match (depending on your settings almost) anything, but only a single character. ? will make the preceding element optional, i.e. appearing not at all or exactly once. * will match the preceding element multiple times, i.e. not at all or an unlimited amount of times. This will match as many characters as possible. If you combine both to *? you'll get a ungreedy match, essentially matching as few characters as possible (down to 0).

    Edit: As I read you only want pass and the complete string, depending on your implementation/language, the following should be enough: ^.*(\bpass\b).*?$ (again, the ungreedy match might be swapped with the greedy one). You'll get the whole expression/match as group 0 and the first defined match as group 1.

提交回复
热议问题