In general terms I want to find in the string some substring but only if it is contained there.
I had expression :
^.*(\\bpass\\b)?.*$
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.
A period only matches a single character, so you're
^.(\bpass\b)?.$
is matching:
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).
Use this one:
^(.*?(\bpass\b)[^$]*)$
Check the demo.
More explanation:
┌ first capture
|
⧽------------------⧼
^(.*?(\bpass\b)[^$]*)$
⧽-⧼ ⧽---⧼
| ⧽--------⧼ |
| | └ all characters who are not the end of the string
| |
| └ second capture
|
└ optional begin characters