Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 17th, 2012  |  syntax: None  |  size: 1.33 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. string convert with python re
  2. >>> line = "  abcn  defnn  ghin  jkl"
  3. >>> print line
  4.   abc
  5.   def
  6.  
  7.   ghi
  8.   jkl
  9.        
  10. >>> print "  abcdefnn  ghijkl"
  11.   abcdef
  12.  
  13.   ghijkl
  14.        
  15. re.sub('(?P<word1>[^ns])ns*(?P<word2>[^ns])', 'g<word1>g<word2>', line)
  16.        
  17. >>> re.sub('(?P<word1>[^ns])ns*(?P<word2>[^ns])', 'g<word1>g<word2>', line)
  18. Out: '  abcdefghijkl'
  19.        
  20. newline = re.sub(r"(?<!n)n[ t]*(?!n)", "", line)
  21.        
  22. (?<!n) # Assert that the previous character isn't a newline
  23. n      # Match a newline
  24. [ t]*  # Match any number of spaces/tabs
  25. (?!n)  # Assert that the next character isn't a newline
  26.        
  27. >>> line = "  abcn  defnn  ghin  jkl"
  28. >>> newline = re.sub(r"(?<!n)n[ t]*(?!n)", "", line)
  29. >>> print newline
  30.   abcdef
  31.  
  32.   ghijkl
  33.        
  34. line = "  abcn  defnn  ghin  jkl"
  35. print re.sub(r'n(?!n)s*', '', line)
  36.        
  37. >>>  re.sub(r'([^n])n(?!n)s*', r'1', line)
  38. '  abcdefnn  ghijkl'
  39.        
  40. >>> line = "  abcn  defnn  ghin  jkln"
  41. >>> re.sub("([ ])|((?:[^n])n(?:[^n]))","",line)
  42. 'abdefnnghjkln'
  43. >>>
  44.        
  45. >>> re.sub("([ t])|((?:[^n])n(?:[^n]))","",line)
  46.        
  47. >>> ''.join(x if 'nn' in x else x[:-1] for x in line.expandtabs(1).split(' ') if x != '')
  48. 'abcdefnnghijkl'
  49.        
  50. >>> import re
  51. >>> line = "  abcn  defnn  ghin  jkl"
  52. >>> print re.sub(r'(S+)ns*(S+)', r'12', line)
  53.   abcdef
  54.  
  55.   ghijkl
  56.        
  57. >>> print re.sub(r'(?P<word1>[^ns]+)ns*(?P<word2>[^ns]+)', r'g<word1>g<word2>', line)
  58.   abcdef
  59.  
  60.   ghijkl