Regex Tips

03 May 2022 - nicolas

some tips about regular expressions along my way of using these wonderful tools.

class equivalent
\d [0-9]
\s [\r\n\t\f\v ]
\S [^\r\n\t\f\v ]
\w [a-zA-Z0-9_]

positive look behind:

(?<=myPatternToHideHere)myPatternToKeepHere

useful when I’m using a pattern to find where the item I’m looking for is, but without keeping this pattern in the result.

for instance to extract values from a file knowing the property name (here some yaml):

cat << EOF | grep -oP '(?<=name: ).+|(?<=quantity: ).+'
fruits:
    -
        name: apple
        color: red
        quantity: 2
    -
        name: orange
        color: orange
        quantity: 46
    -
        name: banana
        color: yellow
        quantity: 77
EOF

will display:

apple
2
orange
46
banana
77