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:
(\d+)\d{3}
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:(\d+)\d{3}.+
Explanation:
"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:
(?s).+?\s\w+:\s+(\d+)\d{3}.+
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:
http://www.tutorialspoint.com/java/java_regular_expressions.htm
http://www.vogella.com/articles/JavaRegularExpressions/article.html
http://en.wikipedia.org/wiki/Regular_expression
http://gskinner.com/RegExr/ (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 comment:

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

    How is the actual progress for this issue?

    :D :D :D

    ReplyDelete