sudheer singh
sudheer singh

Reputation: 922

How to find a word left of a specific word if it exists else return the last word in regex

For example,

MR-L6LQN-LP MR-L6LQN-LQ Way

should return MR-L6LQN-LQ here the specific word is 'Way' if the string is

MR-L6LQN-LP MR-L6LQN-LQ

output should be

MR-L6LQN-LQ

I think lookahead ideas would come in handy but am not able to work it out. Please suggest regex only solution.

Upvotes: 0

Views: 34

Answers (1)

anubhava
anubhava

Reputation: 785108

You can use this regex with a positive lookahead:

\b[A-Z0-9-]+(?=\s+Way|$)

RegEx Demo

RegEx Breakup:

  • \b: Assert word boundary
  • [A-Z0-9-]+: Match one or more of uppercase letters, digits or hyphens
  • (?=\s+Way|$): Positive Lookahead to assert we have spaces and Way ahead or end of line.

Upvotes: 1

Related Questions