0

I need a regex expression for matching a word that immediately precedes a keyword, but doesn't match the keyword itself. For example, in the following text:

"this is some text keyword"

the regex expression should match "text" (assuming "keyword" is the keyword). I should also note that the keyword will always appear as the last word on a line. So far I've come up with this regex:

((?:\S+\s)?\S*keyword\n)

but that matches both the preceding word and the keyword itself (so in the above example it would match "text keyword" instead of just "text"). Does anyone have any advice for this? I'm still learning regex. Thank you!!

davidstern
  • 31
  • 1
  • 4

2 Answers2

5

Code

See regex in use here

\w+(?= +keyword\b)

Results

Input

this is some text keyword

Output

Match only shown below

text

Explanation

  • \w+ Match one or more word characters
  • (?= +keyword\b) Positive lookahead ensuring what follows matches the following
    • + Match one or more spaces (note that there's actually a space before the + but SO doesn't show it)
    • keyword Match this literally
    • \b Assert position as a word boundary
ctwheels
  • 21,901
  • 9
  • 42
  • 77
0

Use this (?m)\w+(?=\h+keyword$) if keyword needs to be last on the line.