Valentyn
Valentyn

Reputation: 612

How to union 2 regex expression?

I have two regex expressions:

1) egrep \\.$./lab1.txt - returns a lines ending with a dot

2) egrep '^\w+[aeiou]\b' ./lab1.txt - returns a lines where the first word ends with a vowel

I need to join this expressions. So, I need to return a lines ending with a dot AND where the first word ends with a vowel. How can I do this?

My demo txt file (lab1.txt):

Hello world
Hello world.
London is the capital of GB.
Oslo is the capital of Norway
Oslo is the capital of Norway.

So, the final expression should return:

Hello world.
Oslo is the capital of Norway.

Upvotes: 1

Views: 1116

Answers (2)

dognose
dognose

Reputation: 20889

To answer the original question:

You can use a lookahead-assertion:

  • Match any line (^.*?$)
  • Match any line ending with a dot (^.*?\.$)
  • but only if it's preceeded by a first word wovel: (?=^\w+[aeiou]\b)^.*?\.$

All together:

(?=^\w+[aeiou]\b)^.*?\.$

Regular expression visualization

Debuggex Demo

(requires multiline mode, if the whole input is a single string, not sure if egrep is working line-wise, but would assume it.)

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93636

Don't combine the regexes. Pipe the output from one invocation of egrep into another invocation of egrep.

egrep '\.$' ./lab1.txt | egrep '^\w+[aeiou]\b'

Upvotes: 1

Related Questions