Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use regex for matching with a condition?

Tags:

regex

vim

I posted this question on super user and I was suggested to post this question on stackoverflow.

I really like vim and today I faced with the intresting problem and I think it can be done via regexp but I can't form out proper one.

I've got a very big sql-file. It consolidates many different queries. File has content with something like this:

select * from hr.employees, oe.orders, oe.order_items
select * from hr.employess, oe.orders, hr.job_history
select * from oe.customers, oe.orders, hr.employees
select * from hr.employees, hr.departments, hr.locations

How can I select only that lines, which has only one match with hr. on the line?. For example above it will be first and third lines.

like image 706
Alexander Myshov Avatar asked Feb 03 '26 07:02

Alexander Myshov


2 Answers

Sure, it is possible to match such lines. This pattern matches:

^\%(\%(hr\.\)\@!.\)*hr\.\%(\%(hr\.\)\@!.\)*$

Some people like to reduce the amount of backslash-escaping by using the very magic switch \v. Then the same pattern becomes

\v^%(%(hr\.)@!.)*hr\.%(%(hr\.)@!.)*$

(Here I used non-capturing parentheses \%(...\) but capturing parentheses \(...\) would work just as well.)

The question is: What do you want to do with these lines? Delete them?

In that case you could use the :global command:

:g/\v^%(%(hr\.)@!.)*hr\.%(%(hr\.)@!.)*$/d

More information at

  • :h :global
  • :h /\v
  • :h /\%(
  • :h /\@!
like image 93
glts Avatar answered Feb 05 '26 00:02

glts


To check if line contains only single occurrence of hr. use regex pattern

^(?=.*\bhr\.)(?!.*\bhr\..*\bhr\.).* with m modifier. I suggest to use grep -P utility.

Regular expression visualization

like image 24
Ωmega Avatar answered Feb 04 '26 23:02

Ωmega



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!