Using Regexp Correctly

I am trying to parse the output from the ps command using a regular expression but it is currently not working. The ps command is invoked with the following arguments:

$ ps -eo min_flt,maj_flt,%cpu,%mem,rss,stat,cmd --sort=-maj_flt

Sample output looks as follows:

343 0 0.0 0.0 3936 R ps -eo min_flt,maj_flt,%cpu,%mem,rss,stat,cmd --sort=-maj_flt

and here is the regular expression I am using:

/^(.?)[\s]+(.?)[\s]+(.?)[\s]+(.?)[\s]+(.?)[\s]+(.?)[\s]+(.?)[\s]+(.?)$/gm

the code follows:

pattern := /^(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)$/gm
regex, _ := regexp.Compile(pattern)
match := regex.FindStringSubmatch(ps_line_str)

but nothing is matched. Please not that the regex pattern works on Regular Expressions 101 at https://regex101.com and provides the following match information:

Match 1   0-93  343      0  0.0  0.0  3936 R    ps -eo min_flt,maj_flt,%cpu,%mem,rss,stat,cmd --sort=-maj_flt
Group 1   0-3    343
Group 2   9-10   0
Group 3   12-15  0.0
Group 4   17-20  0.0
Group 5   22-26  3936
Group 6   27-28  R
Group 7   32-34  ps 
Group 8   35-93  -eo min_flt,maj_flt,%cpu,%mem,rss,stat,cmd --sort=-maj_flt

and one more piece of information, the regular expression worked fine when it it had four less capture groups and ps was invoked as follows:

$ ps -eo min_flt,maj_flt,%mem,cmd --sort=-maj_flt

the output looked like this:

1154 0 0.0 ps -eo min_flt,maj_flt,%mem,cmd --sort=-maj_flt

and the code like this:

pattern := `^(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)$`
regex, _ := regexp.Compile(pattern)
match := regex.FindStringSubmatch(ps_line_str)

and the match would successfully finding all the groups.

Any help would be much appreciated.

Best Regards,

Daryl

I posted too soon as I have just found the answer on the https://regex101.com site. They have a sidebar menu “Flavors” where you can select the language you are using. When I changed it to Golang the regex was changed as follows:

^(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)[\s]+(.*?)$

and now the code is working again. I’m posting this followup in case anyone runs into a similar problem.

Thanks,

Daryl

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.