Jivex5k
Jivex5k

Reputation: 121

lua pattern, exclusion doesn't work with end of string

Maybe exclusion is not the correct term, but I'm talking about using the following in lua's string.find() function :

[^exclude]

It doesn't seem to work if the character is followed by nothing, IE it's the last character in the string.

More specifically, I'm getting a list of processes running and attempting to parse them internally with LUA.

root@OpenWrt:/# ps | grep mpd
 5427 root     21620 S    mpd /etc/mpd2.conf
 5437 root     25660 S    mpd

This wouldn't be an issue if I could expect a \n every time, but sometimes ps doesn't list itself which creates this issue. I want to match:

5437 root     25660 S    mpd

From this I will extract the PID for a kill command. I'm running an OpenWRT build that doesn't support regex or exact options on killall otherwise I'd just do that.

(%d+ root%s+%d+ S%s+mpd[^ ])

The above pattern does not work unfortunately. It's because there is no character after the last character in the last line I believe. I have also tried these:

(%d+ root%s+%d+ S%s+mpd$)

The above pattern returns nil.

(%d+ root%s+%d+ S%s+mpd[^ ]?)

The above pattern returns the first process (5427)

Maybe there is a better way to go about this, or just a simple pattern change I can make to get it to work, but I can't seem to find one that will only grab the right process. I can't go off PID or VSZ since they are variable. Maybe I'll have to see if I can compile OpenWRT with better killall support.

Anyways, thanks for taking the time to read this, and if this is a duplicate I'm sorry but I couldn't find anything similar to my predicament. Any suggestions are greatly appreciated!

Upvotes: 3

Views: 1090

Answers (1)

danielgpm
danielgpm

Reputation: 1672

Given:

local s = [[5427 root     21620 S    mpd /etc/mpd2.conf
5437 root     25660 S    mpd]]

The following pattern

string.match(s,"(%d+)%s+root%s+%d+%s+S%s+mpd[%s]-$")

returns: 5437 root 25660 S mpd

whereas this:

string.match(s,"(%d+%s+root%s+%d+%s+S%s+mpd[%s]%p?[%w%p]+)")

returns:

5427 root 21620 S mpd /etc/mpd2.conf

Upvotes: 4

Related Questions