Narendra Rawat
Narendra Rawat

Reputation: 363

How to match two strings before a specific string

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

Answers (2)

user4227915
user4227915

Reputation:

An alternative to take the first two names:

\w*\s\w*(?=\sJ\.)

Regex live here.

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

Kasravnd
Kasravnd

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

Related Questions