code_junkie

Python Regular Expressions to implement string unescaping

Nov 10th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. >>> import re
  2. >>> mystring = r"This is n a test r"
  3. >>> p = re.compile( "\\(\S)" )
  4. >>> p.sub( "\1", mystring )
  5. 'This is n a test r'
  6. >>> p.sub( "\\\1", mystring )
  7. 'This is \n a test \r'
  8. >>> p.sub( "\\1", mystring )
  9. 'This is \1 a test \1'
  10.  
  11. >>> mystring = r"This is n a test r"
  12. >>> mystring.decode('string-escape')
  13. 'This is n a test r'
  14. >>> print mystring.decode('string-escape')
  15. This is
  16. a test
  17. >>>
  18.  
  19. "\n" == r"n"
  20.  
  21. >>> import re
  22. >>> mystring = r"This is \n a test \r"
  23. >>> p = re.compile( r"[\][\](.)" )
  24. >>> print p.sub( r"\1", mystring )
  25. This is n a test r
  26. >>>
  27.  
  28. >>> d = {'n':'n', 'r':'r', 'f':'f'}
  29. >>> p = re.compile(r"[\]([nrfv])")
  30. >>> print p.sub(lambda mo: d[mo.group(1)], mystring)
  31. This is
  32. a test
  33. >>>
  34.  
  35. This is \n a test \r
  36.  
  37. This is \n a test \r
  38.  
  39. This is n a test r
  40.  
  41. 'This is \n a test \r'
  42.  
  43. This is n a test r
  44.  
  45. >>> mystring = r"This is n a test r"
  46. >>> mystring
  47. 'This is \n a test \r'
  48. >>> print mystring
  49. This is n a test r
  50.  
  51. >>> mystring = r"This is n ridiculous"
  52. >>> print mystring
  53. This is n ridiculous
  54. >>> p = re.compile( r"\(S)" )
  55. >>> print p.sub( 'bloody', mystring )
  56. This is bloody ridiculous
  57. >>> print p.sub( r'1', mystring )
  58. This is n ridiculous
  59. >>> print p.sub( r'\1', mystring )
  60. This is 1 ridiculous
  61. >>> print p.sub( r'\1', mystring )
  62. This is n ridiculous
  63.  
  64. This is
  65. ridiculous
Add Comment
Please, Sign In to add comment