August 6, 2013

RegEx Tips

Starting from CoolTool v4.5 you can tweak custom label with java regular expressions (RegEx).
For example, default custom label aimed to /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq that shows current cpu freq in kHz. To convert it to MHz we can use regex:
This regex converts "800000" to "800".

Another example. We have temperature sensor data "Result:40000 Raw:20000" and we want to extract "40" value (40000/1000). We can use such kind of regex:
"Result:" - just removing matched text
"(\d+)" - grouped expressions always stays untouched.  \d means digits. + means 1 to "many" :)
"\d{3}" - means 3 digits. so "000" will be removed.
".+" - dot means any symbol and "+" means any amount of symbols (except 0). In our case it matched to " Raw:20000".
Please note that required value should be enclosed into the regex group #1 ($1 replacement pattern).
Update: Starting from v5.3 you can modify replacement pattern to whatever you want.

Example 3. Lets try to parse /proc/meminfo:
MemTotal:         897600 kB
MemFree:          139872 kB
Buffers:           18000 kB
Cached:           338656 kB
SwapCached:            0 kB

Lets say we need MemFree value in MBs:
Result will be "139"
"(?s)" is specific "dotall" mode that indicates whether . matches new-line characters
".+?" means that we need match as few symbols as can.
"\s" - space symbol.
"\w+" - any amount of word symbols (a-zA-z0-9_).
":" - colon in "MemFree:"
"\s+" - few spaces.
"(\d+)" - our value in the expression group. Don't forget to create at least one group!
"\d{3}" - "872" value of "139872".
".+" - rest of the text (including line separators, because we used "dotall" mode).

To learn more about regular expressions, patterns, groups please follow these links: (Highly recommend!) You can simulate CoolTool behavior there. Just paste your regex in the first input field and "$1" replacement parameter in the second one (see screen shot).

If you don't want any filtering, just leave regex fields blank.
If you expecting problems with creating your own regex, feel free to email me.

Postscript: sorry for my ugly English :)


  1. Hi. Excited waiting the multi line parse :D

    How is the actual progress for this issue?

    :D :D :D

  2. To change from Mhz to Ghz when the length of the numeric string changing frequently, as is the case with the CPU frequency, this works;

    (\d?)(\d)\d{5}$ It will convert 1869400 to 1.8 for 1.8 Ghz
    (\d?)(\d{2})\d{4}$ Will make it 1.86 Ghz

    And it will work to convert 347000 to .3 Ghz or. 34 Ghz.

    (\d)(\d)\d+ Converts the battery voltage to n.n format (ie, 3.8v) also.