Raspberry-Jam
Raspberry-Jam

Reputation: 3

Lua pattern matching a number format and not capturing earlier numbers

I want to capture resolutions and refresh rate outputs from xrandr -q. Specifically, these numbers are formatted as xx.xx or xxx.xx, where there will always be 2 numbers after a decimal point, but sometimes 2 or 3 numbers before it as well. I want to capture each value individually to be able to store them for later use.

4 lines of typical command output would look like this:

   3440x1440     59.97 +  99.98*   49.99  
   2560x1440     59.95  
   2560x1080     60.00    59.94  
   1920x1080     60.00    59.94    50.00 

I've been able to get the resolution using string.match(xrandr[i], "^.-%s(%d.-x.-%s)") where xrandr is an array containing each line of command output. My current attempt for getting the refresh rates individually looks like this: string.gmatch(xrandr[i], "%s.-(%d.-%..-%d%d)"). This almost works, but for every resolution, it captures both the resolution and the first refresh rate together, and then captures any following separately. When I try to print the intentionally captured resolution followed by each of its supported refresh rates, it looks like this:

3440x1440 
3440x1440     59.97
99.98
49.99
2560x1440 
2560x1440     59.95

Where the resolution is captured, but then it's captured again with the first refresh rate. Instead I'd like to get this:

3440x1440 
59.97
99.98
49.99
2560x1440 
59.95

So how can I avoid re-capturing the resolution while also getting each refresh rate invididually?

Upvotes: 0

Views: 599

Answers (1)

Piglet
Piglet

Reputation: 28950

Your patterns are way to complicated.

Resolution: `"%d+x%d+"

%d any digit

%d+ one or more digits

x character x

Refresh rates: "%d+%.%d+"

%. a dot (escaped magic character . with %, otherwise . means any character)

In one go:

local a = "1234x5678 12.34 56.78"

for match in a:gmatch("[0-9x.]+") do print(match) end

[0-9x.] is a class of characters. it matches any occurance of digits 0 to 9, . or x

So "[0-9x.]+" matches any sequence of digits that may also contain a . or an x

Upvotes: 2

Related Questions