Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match but not include a word before another word

Tags:

regex

I have two specific words in a line say dog and cat.

And say dog appears before cat.

How do I make a regex which tells me all the lines containing dog and cat, but show just the words after dog till cat, including cat, but NOT dog.

like image 968
hrishi1990 Avatar asked Oct 01 '22 09:10

hrishi1990


1 Answers

Option 1: Lookbehind

(?<=dog).*?cat

Details:

  • The (?<=dog) lookbehind asserts that what precedes the current position is dog
  • .*? lazily matches all characters up to...
  • cat matches literal characters

Option 2: \K (PCRE, Perl, Ruby 2+)

dog\K.*?cat

The \K tells the engine to drop what was matched so far from the final

Option 3: Capture Group (JavaScript and other engines that don't support the other two options)

dog(.*?cat)

The parentheses capture what you want to Group 1. You have to retrieve the match from Group 1 in your language.

like image 162
zx81 Avatar answered Oct 10 '22 06:10

zx81