
Untitled
By: a guest on
May 17th, 2012 | syntax:
None | size: 1.33 KB | hits: 14 | expires: Never
string convert with python re
>>> line = " abcn defnn ghin jkl"
>>> print line
abc
def
ghi
jkl
>>> print " abcdefnn ghijkl"
abcdef
ghijkl
re.sub('(?P<word1>[^ns])ns*(?P<word2>[^ns])', 'g<word1>g<word2>', line)
>>> re.sub('(?P<word1>[^ns])ns*(?P<word2>[^ns])', 'g<word1>g<word2>', line)
Out: ' abcdefghijkl'
newline = re.sub(r"(?<!n)n[ t]*(?!n)", "", line)
(?<!n) # Assert that the previous character isn't a newline
n # Match a newline
[ t]* # Match any number of spaces/tabs
(?!n) # Assert that the next character isn't a newline
>>> line = " abcn defnn ghin jkl"
>>> newline = re.sub(r"(?<!n)n[ t]*(?!n)", "", line)
>>> print newline
abcdef
ghijkl
line = " abcn defnn ghin jkl"
print re.sub(r'n(?!n)s*', '', line)
>>> re.sub(r'([^n])n(?!n)s*', r'1', line)
' abcdefnn ghijkl'
>>> line = " abcn defnn ghin jkln"
>>> re.sub("([ ])|((?:[^n])n(?:[^n]))","",line)
'abdefnnghjkln'
>>>
>>> re.sub("([ t])|((?:[^n])n(?:[^n]))","",line)
>>> ''.join(x if 'nn' in x else x[:-1] for x in line.expandtabs(1).split(' ') if x != '')
'abcdefnnghijkl'
>>> import re
>>> line = " abcn defnn ghin jkl"
>>> print re.sub(r'(S+)ns*(S+)', r'12', line)
abcdef
ghijkl
>>> print re.sub(r'(?P<word1>[^ns]+)ns*(?P<word2>[^ns]+)', r'g<word1>g<word2>', line)
abcdef
ghijkl