Regex find word in the string

前端 未结 3 877
孤街浪徒
孤街浪徒 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.

    0 讨论(0)
  • 2020-12-28 14:33

    A period only matches a single character, so you're

    ^.(\bpass\b)?.$
    

    is matching:

    • Start of input
    • A single character
    • Optionally
      • Word boundary
      • "pass"
      • Word boundary
    • Single char
    • End of input

    which I would not expect to match "high pass h3" at all.

    The regular expression:

    pass
    

    (no metacharacters) will match any string containing "pass" (but then so would a "find string in string" function, and this would probably be quicker without the complexities of a regex).

    0 讨论(0)
  • 2020-12-28 14:42

    Use this one:

    ^(.*?(\bpass\b)[^$]*)$
    
    1. First capture for the entire line.
    2. Second capture for the expected word.

    Check the demo.

    More explanation:

              ┌ first capture
              |
     ⧽------------------⧼
    ^(.*?(\bpass\b)[^$]*)$
      ⧽-⧼          ⧽---⧼
       | ⧽--------⧼  |
       |     |       └ all characters who are not the end of the string
       |     |
       |     └ second capture
       |
       └ optional begin characters
    
    0 讨论(0)
提交回复
热议问题