Reputation: 13
This \[(.*?)\]
gets string between [
and ]
. Now I want to get string between one word and another one. I've tried \wword1(.*?)\wword2
, no success. Help me, what am I doing wrong?
String example:
The engine word1 has successfully word2 matched the word is in our string, skipping the two earlier occurrences of the characters i and s. If we had used the regular expression is, it would have matched the is in This.
Output example: has succesfully
Upvotes: 1
Views: 218
Reputation: 163362
When you add \w
to the pattern, it will match a word character and it is expected.
What you might do is remove that and match 1+ times a whitespace character after the first word and before the second word.
Then your match in the first capturing group:
\bword1\s+(.*?)\s+word2\b
Explanation
\b
Word boundaryword1
Match literaly\s+
Match 1+ times a whitespace char(.*?)
Capture in a group any char 0+ times non greedy\s+
Match 1+ times a whitespace charword2
Match literally\b
Word boundaryUpvotes: 0
Reputation: 1271
this
[(.?)]
gets string between[
and]
.
No it doesn't, it should be \[[^\]]*\]
to get any string between [ and ]
The solution is:
\bword1(.*?)\bword2
\w
is a word character [A-Za-z)-9]
and some more. \b
is a word boundary, what you are looking for. It might even be
\bword1\b(.*?)\bword2\b
Upvotes: 0
Reputation: 38502
You can do this way-
word1 ([a-zA-Z\s]+) word2
OR
Your way after removing unnecessary \w
before and after
word1 (.*?) word2
REGEX: https://regex101.com/r/fsp3FS/20
Upvotes: 0