Alexander
Alexander

Reputation: 13

Get a string between two words

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

Answers (4)

Kevin Chen
Kevin Chen

Reputation: 122

Try this:

(?<=word1)(stringbetween)(?=word2)

Upvotes: 1

The fourth bird
The fourth bird

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

Regex demo

Explanation

  • \b Word boundary
  • word1 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 char
  • word2 Match literally
  • \b Word boundary

Upvotes: 0

Roemer
Roemer

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

A l w a y s S u n n y
A l w a y s S u n n y

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

Related Questions