我想处理2个案例:
(string)
- > string
@string otherStuff
- > string
怎么做?
答案 0 :(得分:2)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '(string)').groups()
('string', None)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '@string otherStuff').groups()
(None, 'string')
答案 1 :(得分:1)
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
答案 2 :(得分:0)
这对你有用吗?
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'