user837208
user837208

Reputation: 2577

Regex match first instance only

For some reason I am not able to use lazy matching.

Here is the text -

 806 ?        Ss     0:00 /usr/sbin/apache2 -k start
  823 ?        S      0:00  \_ /usr/sbin/apache2 -k start
  824 ?        S      0:00  \_ /usr/sbin/apache2 -k start
  825 ?        S      0:00  \_ /usr/sbin/apache2 -k start
  826 ?        S      0:00  \_ /usr/sbin/apache2 -k start
  827 ?        S      0:00  \_ /usr/sbin/apache2 -k start

and I want to match only first line which has "apache2" i.e.

806 ?        Ss     0:00 /usr/sbin/apache2 -k start

my regex looks like this -

(apache)?

but it doesn't seem to be working- its matching all instances. What's wrong?

Upvotes: 0

Views: 933

Answers (1)

mkataja
mkataja

Reputation: 990

Your regex (apache)? means approximately "match either apache or not apache", so it will obviously match everything.

You didn't specify which programming language or regex flavor you are using, but this regex would match a whole row containing the word apache:

.*apache.*

This would of course match all the lines containing the word apache, so it's up to you to use the programming language you are using to get only the very first match.

Note: If your regex flavor of choice matches newlines with the dot, then you might need to go in multiline mode and add the start of line and end of line anchors, like this:

^.*apache.*$

(and then remember to turn the multiline mode on!)

Upvotes: 1

Related Questions