Tuesday, 25 February 2014

Sunday, 23 February 2014

Python Regex Expression(Regex!!)



Introduction
Matching text patterns

Support
Python module supports re module for regex support
Visit Of Regex
Search expression
Python regular expression can be written as
match = re.search(pattern, string)

Search pattern takes following parameters
a) pattern: A regular expression pattern
b) string: A string in which we wanna find regex pattern

Return by this method:
a) It will return a match object is search is successful
b) Else, None

Lets consider an example,  
>>> import re                          # Import re module
>>> pattern = r'word'                  # Define regex pattern
>>> string = 'Test word'               # Define string on which implementation of search we want
>>> match = re.search(pattern, string)  # Syntax of search in regex(regular expression)
>>> match                               # Return an object after searching
<_sre.SRE_Match object at 0x018A1B10>  
>>> if match:
...     print 'Matched, ', match.group() # If matched, print group of words
... else:
...     print 'Opss not found..'
...
>>> Matched,  word                      # Return matched words :)

Have you noted 'r' while defining the patterns. This is actually called raw string('r') which passes through backslashes without change. r prefix (e.g. r"\d+") is actually used for raw strings in Python. In a raw string you don't have to escape backslashes with \\ (e.g. "\\s+" equals r"\s+"). On python terminal
>>> "\\s+"
'\\s+'
>>> r'\s+'
'\\s+'
So while it's a very good convention to prefix all regular expressions with r, it's not technically necessary when an expression doesn't have any backslashes (e.g. "[0-9a-z]").

Escape sequences are:
     
Basic Patterns
Following are the basic patterns in regex:

  • a, X, 9, < - Ordinary characters just match them selves. Meta characters dont match them selves.  11 metacharacters that must always be preceded by a backslash, \, to be used inside of the expression  
  • . (a period) - matches any single character except newline '\\n' 
  • \\w (lowercase w) - matches a "word" character: a letter or digit or underbar [a-zA-Z0-9_]
  • \\b  -  boundary between word and non-word
  • \\s (lowercase s) - matches a single whitespace character. space, newline, return, tab, form ['\\n \\r\\t' ]
  • \\t, \\n, \\r - tab, newline, return(respectively) 
  • \\d -  boundary between word and non-word
  • ^ = start, $ = end  -  match the start or end of the string
Some basic ExampleSome basic examples on python terminal:

>>> match = re.search(r'.', 'Test word')
>>> match.group()
>>> 'T'
>>> match = re.search(r'..', 'Test word')
>>> match.group()
>>>'Te'
>>> match = re.search(r'...', 'Test word')
>>> match.group()
>>>'Tes'
>>> match = re.search(r'.w', 'Test word')
>>> match.group()
' w'
>>> match = re.search(r't.', 'Test word')
>>> match.group()
't '
>>> match = re.search(r'.w.', 'Test word')
>>> match.group()
' wo'
>>> match = re.search(r'wor..', 'Test word')
>>> match.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> match = re.search(r'wor.', 'Test word')
>>> match.group()
'word'
>>> match = re.search(r'\d', '1001 Test word')
>>> match.group()
'1'
>>> match = re.search(r'\d\d', '1001 Test word')
>>> match.group()
'10'
>>> match = re.search(r'\d\d\d', '1001 Test word')
>>> match.group()
'100'
>>> match = re.search(r'\w\w', '1001 Test word')
>>> match.group()
'10'
>>> match = re.search(r'\d\d\d', '1001 Test word @!#')
>>> match = re.search(r'\w\w', '1001 Test word @!#')
>>> match.group()
'10'
>>> match = re.search(r'\w\w\w', '@@abcd!!')
>>> match.group()
'abc'
>>> match = re.search(r'\w\w', '@#1$ 1001 Test word')
>>> match.group()
'10'

Repetition

  • (+) - One(1) or more occurances of pattern from left
  • (*) - Zero(0) or more occurances of the pattern from left
  • (?) Zero(0) or One(1) of the pattern from left
So basically it means that (+, *), match string from left most and go far as possible.

Examples

>>> match = re.search(r'Te+', 'Teest Word')
>>> match.group()
'Tee'
>>> match = re.search(r'Te+', 'Teeeast Word')
>>> match.group()
'Teee'
>>> match.group()
'Te'
>>> match = re.search(r'\d\s*\d\s*\d', 'sfad1 2   3asdxx')
>>> match.group()
'1 2   3'
>>> match.group()
'1 2   3'
>>> match = re.search(r'\d\s*\d\s*\d\s*', '1 2   3    ')
>>> match.group()
>>> match = re.search(r'\d\s*\d\s*\d', '    1234         ')
>>> match.group()
'123'
>>> match = re.search(r'\d\s*\d\s*\d\s*', '1 2   3    ')
>>> match.group()
'1 2   3    '
>>> match = re.search(r'\d\s*\d\s*\d\s*', '     123             ')
>>> match.group()
'123             '
>>> match = re.search(r'\s*\d\s*\d\s*\d', '    1234         ')
>>> match.group()
'    123'

Find E-mails in an example

>>> match = re.search(r'\w+@\w+', 'This is the search for abc@domian example')
>>> match.group()
'abc@domian'

Usage of square brackets

  • Used to indicate set of characters, i.e. [abc] matches a or b or c
  • The codes \\w, \\s etc. work inside square brackets too with the one exception that dot (.) just means a literal dot. For the emails problem, the square brackets are an easy way to add '.' and '-' to the set of chars which can appear around the @ with the pattern r'[\\w.-]+@[\\w.-]+' to get the whole email address
>>> match = re.search(r'[\w.]+@[\w.]', 'This is the search for abc@domian example')
>>> match.group()
'abc@d'
>>> match = re.search(r'[\w.]+@[\w.]+', 'This is the search for abc@domian example')
>>> match.group()
'abc@domian'
>>> match = re.search(r'[\w.]+@[\w.]+', 'This is the search for abc@domian.com example')
>>> match.group()
'abc@domian.com'
>>> match = re.search(r'[\w.-]+@[\w.]+', 'This is the search for abc-def@domian.com example')
>>> match.group()
'abc-def@domian.com'

Usage Of Parenthesis()

  • Allow to pick part of matching text.
  • Do not change the pattern  text.
  • Establish groups of matched text. like match.group(1), match.group(2) etc
  • Plain match.group() match whole text as usual
For an example,

>>> match = re.search('([\w.-]+)@([\w.-]+)', 'This is an example of group matching abc-def@gmail.com')
>>> match.group()    # Whole plain match
'abc-def@gmail.com'
>>> match.group(1)   # First match of group
'abc-def'
>>> match.group(2)   # Second match of group
'gmail.com'

findall Function
Match all pattern in a text.

  • re.search() - Find first match  for a pattern.
  • findall() - Match all string and return list of matched content.
>>> match = re.findall('[\w.-]+@[\w.-]+', 'An exmapple of findall abc-def@gmail.com, xyz-uvw@yahoo.com')
>>> match
['abc-def@gmail.com', 'xyz-uvw@yahoo.com']

findall & Groups

  • () can be combined with findall.
  • If pattern have two or more (), it will return list of tuples. Each tuple represent matched pattern.

Lets take example to view this scenarion
>>> match = re.findall('([\w.-]+)@([\w.-]+)', 'An exmapple of findall abc-def@gmail.com, xyz-uvw@yahoo.com')
>>> match                  # Return list of tuples of matched content with separate groups in a tuple
[('abc-def', 'gmail.com'), ('xyz-uvw', 'yahoo.com')]
>>> match[0]        
('abc-def', 'gmail.com')
>>> match[0][0]
'abc-def'
>>> match[0][1]
'gmail.com'
>>> match[1][0]
'xyz-uvw'
>>> match[1][1]
'yahoo.com'

Thanks

Tuesday, 18 February 2014

Gotchas about __str__ and __repr__

Many of python developers confused with the gotcha of __str__ and __repr__ in-built function of python.

So lets's try to clear this.

For new beginners

  • __str__ can be treated as informal string representation of an object.
  • __repr__ can be taken as formal representation of an object
Confused!! :P
No need to worry, lets take help of lovable python terminal. 

Consider an example of number


As from the above result str() and repr() are same.

Now consider an example of string


From above results its clear that while evaluating result of str & repr are different and not valid in case of str representation of a string
Hope now its clear.

Tuesday, 21 January 2014

Paste In Putty For New Users


Sometimes its a gotcha, a new user is not able to paste a password in Putty when trying to login. Don't worry here is the simple solution. Copy your password and on putty press Right Click Of Your Mouse where its mention to give password .

Hope its helpful.

Thanks 

Friday, 17 January 2014

Linux Feel On Windows


Scared when saw that I have to work on Windows for my new work. As get habitual to work on Linux platform, so fall in love with this OS. But anyhow found a solution to work on terminal and its command on windows.

If anyone facing the same issue, presenting the solution. Great to install cygwin  from this link http://www.cygwin.com/ . After installing a user can feel the same experience on windows like Linux.

Thursday, 16 January 2014

Dedicated To My Father

पुरानी पेंट रफू करा कर पहनते जाते है,
Branded नई shirt
देने पे आँखे दिखाते है
टूटे चश्मे से ही अख़बार पढने का लुत्फ़ उठाते
है, Topaz के
ब्लेड से दाढ़ी बनाते है
पिताजी आज भी पैसे बचाते है ….
कपड़े का पुराना थैला लिये दूर
की मंडी तक जाते है,
बहुत मोल-भाव करके फल-सब्जी लाते है
आटा नही खरीदते, गेहूँ पिसवाते है..
पिताजी आज भी पैसे बचाते है…
स्टेशन से घर पैदल ही आते है रिक्सा लेने से
कतराते है
सेहत का हवाला देते जाते है बढती महंगाई
पे
चिंता जताते है
पिताजी आज भी पैसे बचाते है ....
पूरी गर्मी पंखे में बिताते है, सर्दियां आने
पर रजाई में
दुबक जाते है
AC/Heater को सेहत का दुश्मन बताते है,
लाइट
खुली छूटने पे नाराज हो जाते है
पिताजी आज भी पैसे बचाते है
माँ के हाथ के खाने में रमते जाते है, बाहर
खाने में
आनाकानी मचाते है
साफ़-सफाई का हवाला देते जाते
है,मिर्च, मसाले और
तेल से घबराते है
पिताजी आज भी पैसे बचाते है…
गुजरे कल के किस्से सुनाते है, कैसे ये सब
जोड़ा गर्व से
बताते है पुराने दिनों की याद दिलाते
है,बचत की अहमियत
समझाते है
हमारी हर मांग आज भी,फ़ौरन पूरी करते
जाते है
पिताजी हमारे लिए ही पैसे बचाते है ...


Note: This poem is not written by me, but I love this poem alot.

Wednesday, 15 January 2014

Absolute Path Vs Relative Path

Hey,

So my friends whats happening? From  last few days was facing an issue to understand the concept of Absolute Path and Relative Path.

So as per the R&D provinding a simple solution for the same.

Absolute Path, basically the location/address of file from root(/) to the specified location. Or in other words, full path of a file/directory from the root(/).
For an example,
/var/www/operx
/home/user/anupam/Books/PythonBooks/

Relative Path, is the location of file related to the present working directory(pwd). Suppose I am inside /home/user/anupam/Books and want to change directory to /home/user/anupam/Books/PythonBooks.
I can use relative path concept to change directory to PythonBooks by,
/home/user/anupam/Books
cd PythonBooks

Note: If you observe there is no / before PythonBooks which indicates it's a relative directory to present working directory.

Is it possible to change /home/user/anupam/Books/PythonBooks/ using absolute path concept via
/home/user/anupam/Books/PythonBooks/

Hope this is useful.

Thanks.

Tuesday, 31 December 2013

!!2014 is waiting Yuhuuuu!!

Hey,

So guys what's your planning, resolutions for this new year that is really waiting for us eagerly. I am wishing you a warm happy prosperous happy new year 2014. God sprinkles your life with lots of smiles, success and yes of course lots of hard work to achieve dreams, aims, goals that all of us decided. Keep smiling and make others happy too. :)

Thursday, 26 December 2013

sudo: /etc/sudoers is mode 0442, should be 0440



This is the common issue faced by Linux users. The issue is as, while running command with help of sudo raises following exceptions
sudo: /etc/sudoers is mode 0442, should be 0440
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

So presenting the solution for the same, run the following command on your terminal.

pkexec chmod 0440 /etc/sudoers

Hope it will help you :)

Wednesday, 25 December 2013

Christmas Is Here

Christmas came early for you and for me
Christmas with no gifts to open
Christmas was cups of tea served early morn
Christmas was being together
Christmas was loving from dusk until dawn
Christmas remembered forever
Christmas was driving through floods for the view
Christmas ‘our planning’ was starting
Christmas our Christmas meant so much to me
Christmas our bitter sweet parting