python regex not able to match strings with back slash involved -


c:\users\dibyajyo>python                                                               python 2.7.9 (default, dec 10 2014, 12:24:55) [msc v.1500 32 bit (intel)] on win32     type "help", "copyright", "credits" or "license" more information.                 >>>                                                                                    >>>                                                                                    >>> import re                                                                          >>> outstring = 'diagnosticpath = fs0:\\efi\\tools'                                    >>> print outstring                                                                    diagnosticpath = fs0:\efi\tools                                                        >>> expstring = 'diagnosticpath = fs0:\\efi\\tools'                                    >>> print expstring                                                                    diagnosticpath = fs0:\efi\tools                                                        >>> matchobj = re.search( expstring, outstring, re.m|re.i)                             >>> if matchobj:                                                                       ...   print matchobj.group()                                                           ...                                                                                    >>> 

both expstring , outstring strings same yet not sure why not finding match...

quote python's re documentation:

regular expressions use backslash character ('\') indicate special forms or allow special characters used without invoking special meaning. collides python’s usage of same character same purpose in string literals; example, match literal backslash, 1 might have write '\\\\' pattern string, because regular expression must \\, , each backslash must expressed \\ inside regular python string literal.

the solution use python’s raw string notation regular expression patterns; backslashes not handled in special way in string literal prefixed 'r'. r"\n" two-character string containing '\' , 'n', while "\n" one-character string containing newline. patterns expressed in python code using raw string notation.

so if use:

expstring = r'diagnosticpath = fs0:\\efi\\tools' 

your code should work.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -