Reputation: 363
I want to match just two strings before a matched string
e.g Rohan pillai J.
Currently i am using :
pattern= (?=\w+ J[.])\w+
Answer - pillai
desired answer - Rohan pillai
Upvotes: 1
Views: 102
Reputation:
An alternative to take the first two names:
\w*\s\w*(?=\sJ\.)
Explaining:
\w*\s # the first word (name) followed by space
\w* # the second word (name)
(?=\sJ\.) # must end with space and "J." - without taking it
Tip: Generally to escape regex metacharacters (like dot .
) we use back-slash. Use character class like [.]
if you want to put emphasis on that character (if you want to make it more visible when you will read this regex).
Upvotes: 1
Reputation: 107287
You need to put the look ahead in trailing :
(\w+) (\w+)(?= J\.)
See demo https://regex101.com/r/wH0oU8/1
Or more general you can use \s
to match any whitespace instead of space :
(\w+)\s(\w+)(?=\sJ\.)
Upvotes: 1