Pages

Saturday 31 March 2012

Really quick REGEX guide

Really quick REGEX guide 

Regular expressions… a bunch of brackets and special characters that nobody understands right? Well not exactly true. Although people tend to interpret them as newly discovered ancient language, Unix/Linux shells, text editors, scripting tools and some development environments understand them perfectly. And if you, as a “puny human“, figure them out, the work that usually takes hours can be reduced to minutes or less. So without any further delay here are the basics you can start with.


BRACKETS []: Used to give a list of possibilities.

EXAMPLE: grep [nN]ame /etc/services - This will find either n or N followed by “ame”. If there is ^ character inside of brackets it means that every parameter included after that character will not be included in search, for example: grep [^Nnt]ame /etc/services – it will not include N, n and t letters in search in front of “ame”. Try it, it will make more sense


PERIODS …: Used to match characters.

EXAMPLE: grep n..e /etc/services – This will match letters n and e with any two characters between them.


ASTERIX *: Used to find zero or more occurrences of a character.

EXAMPLE: grep [nN]e*d /etc/services – This will match Ned, need, nd, neeed.


QUOTES ” “: Used to match one or more blank spaces.

EXAMPLE: grep “a lot” /etc/services – This will match zero or more blank spaces which will account for the common misspelling of “a lot” as “alot”.


SPECIAL CHARACTER ^: Used to match the word when it is located at the beginning of the line.

EXAMPLE: grep ^the /etc/services – This will match any line that starts with the.


SPECIAL CHARACTER $: Used to match the word when it’s located at the end of the line.

EXAMPLE: grep the$ /etc/services – This will match any line that ends with the.


There are a bit more regular expressions, but upper ones are most commonly used. At least by me Thanks for reading.

No comments:

Post a Comment

Twitter Bird Gadget