0

我想处理两种情况:

  1. (string)->string

  2. @string otherStuff->string

如何做呢?

4

3 回答 3

2
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '(string)').groups()
('string', None)
>>> re.search(r'\(([^)]+)\)|@([^ ]+) ', '@string otherStuff').groups()
(None, 'string')
于 2012-04-23T01:05:01.427 回答
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
于 2012-04-23T01:10:47.647 回答
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'
于 2012-04-23T01:05:22.103 回答