Regex Find Word in the String
In General Terms I Want to Find in the String Some Substring but Only If It Is Contained There. I Had Expression: ^. *(\Bpass\B)? .*$ and Test String: High...
In general terms I want to find in the string some substring but only if it is contained there.
I had expression :
^.*(\bpass\b)?.*$
And test string:
high pass h3
When I test the string via expression I see that whole string is found (but group "pass" not):
match : true
groups count : 1
group : high pass h3
But that I needed, is that match has 2 groups : 1: high pass h3 2: pass
And when I test, for example, the string - high h3, I still had 1 group found - high h3
How can I do this?
3 Answers
Use this one:
^(.*?(\bpass\b)[^$]*)$
- First capture for the entire line.
- 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
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:
- 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).