Regular expression cheatsheet
Jump to navigation
Jump to search
This is small collection of regex that patterns I want to document because I think they are useful, at least for me.
Recipies
Match only unknown values
For a serverspec test I needed to write a check where all unknown shell aliases should match in one query without looping. This is what I came up with. I know that the 3 grep patterns could be further reduced.
/^(alias\s+(?!(?:egrep|fgrep|grep|which)=).*/
Which matches only the last 2 highlighted entries but not the leading 4 ones. The highlight can be recalled with $1:
alias egrep= alias grep= alias fgrep= alias which= alias whatever= alias foobar=
Match one or more specific keywords
When writing an parser for the ip addr command I ran into a case where one or more flags had to be gotten before mangling them into an ruby array. The actual code is more complex but for brevity only the relevant part is shown.
/inet.*global\s(?:((?:(?:temporary|permanent|dynamic|secondary|primary|tentative|deprecated)\s+)+))?/
The highlighted matches below would be recalled by $1
inet 10.0.0.1/24 scope global eth0-foo inet 10.0.0.2/24 scope global secondary eth0-foo inet6 2001:db8::16b4/64 scope global temporary dynamic inet6 2001:db8::16b3/64 scope global deprecated dynamic inet6 2001:db8::16b2/64 scope global dynamic