Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Unix (http://www.go4expert.com/articles/unix/)
-   -   Simple Regex Samples (http://www.go4expert.com/articles/simple-regex-samples-t25224/)

lionaneesh 11Mar2011 15:59

Simple Regex Samples
 
Regular expressions commonly known as ‘regex’ provide an abstract and Flexible means to compare strings. It’s mainly used for scrapping and extraction of useful data from strings.

In this tutorial we’ll be looking at some regular expressions using grep in Unix/Linux and how to use them in various situations.

Expressions



How to parse out simple emails from body of a list of emails in your inbox

A simple email list:-

Code:

From: lionaneesh@gmail.com
To : s123@abc.com

Hey Buddy!!!!!!!!!

From : 123@go4expert.com
To :  234@gmail.com

How is the article

From : test@go4expert.com
To :  test@gmail.com

I am a test email

Our target will be to parse out 'From:' types in our email list.

Parse expression:-

Code:

cat mail.txt | grep "^From:*"
Output:-

Code:

From: lionaneesh@gmail.com
From : 123@go4expert.com
From : test@go4expert.com

Find all the words starting with a small letter (non-capitalized) in a given file


small.txt
Code:

aneesh
Aneesh
Dogra
dogra
lioanneesh
Lionaneesh

Regex :-

Code:

cat small.txt | grep "^[a-z]"
Output :-

Code:

aneesh
dogra
lioanneesh

Find all the valid emails in a given text file

emails.txt
Code:

lionaneesh@gmail.com
hello@gmail.com
hell@@gmail.com
hell!@gmail..com
invalid@gmail.comnop

Regex :-

Code:

cat emails.txt | grep "[a-zA-Z0-9._%+-]\+@[a-zA-Z0-9.-]\+\.[a-z]\{2,4\}$
output:-

Code:

lionaneesh@gmail.com
hello@gmail.com

Find all the words in a given file that starts with ‘a’ and ends with ‘h’..

sample_file.txt

Code:

aneesh
shabbir
coderzone
go4expert
anish

Regex :-

Code:

cat sample_file.txt | grep "^[aA].*[hH]$"
Output :-

Code:

aneesh
anish

Eminem is searching for some rhyming words to pull off his rap song..Make him a regex to find some rhyming words rhyming with :-
'life'

We'll be using Unix words text file to pull off this scenario...

Regex :-

Code:

cat /usr/share/dict/words | grep "ife$"
Output :-

Code:

Recife
Yellowknife
afterlife
fife
fishwife
housewife
jackknife
knife
life
midwife
nightlife
penknife
pocketknife
rife
strife
wife
wildlife

Crypt0n is cracking a hash he has figured out that the password starts with j and ends with 2 z's... Make a regex for him to help him with his cracking

Regex :-
Code:

cat /usr/share/dict/words | grep "[j].*[z]\{2\}$"
output :-

Code:

jazz
That’s all for this tutorial…Stay tuned for more!

lionaneesh 11Mar2011 20:35

Re: Simple Regex Samples
 
I hope the viewers like it!!!


All times are GMT +5.5. The time now is 08:32.