我想处理两种情况:
(string)
->string
@string otherStuff
->string
如何做呢?
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '(string)').groups()
('string', None)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '@string otherStuff').groups()
(None, 'string')
import re
def getstring(string):
testforstring = re.search("\((.*)\)",string)
if testforstring:
return testforstring.group(1)
testforstring = re.search("@(.*?)\s+.*",string)
if testforstring:
return testforstring.group(1)
return None
允许您执行以下操作:
>>> print getstring('(hello)')
hello
>>> print getstring('@hello sdfdsf')
hello
这对你有用吗?
In [45]: s='(string)'
In [46]: s = s[1:-1]
In [47]: s
Out[47]: 'string'
和
In [48]: s = '@string otherstuff'
In [49]: s=' '.join(s.split()[1:])
In [50]: s
Out[51]: 'otherstuff'