从引号之间提取字符串

41

我想从用户输入的文本中提取信息。假设我输入以下内容:

SetVariables "a" "b" "c"

我该如何提取第一组引号之间的信息?然后是第二组?第三组呢?

3个回答

66
>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']

2
需要在行末加分号吗? - User
1
@User 很好的发现,四年后没有其他人注意到。需要注意的是,分号(;)允许您在一行上放置两个命令,但这种做法在大多数情况下是不鼓励的。 - WinEunuuchs2Unix

44
你可以对字符串进行 string.split() 操作。如果该字符串使用引号正确格式化(即引号数为偶数),那么列表中的每个奇数值都将包含在引号之间的元素。
你可以对字符串进行 string.split() 操作。如果该字符串使用引号正确格式化(即引号数为偶数),那么列表中的每个奇数值都将包含在引号之间的元素。
>>> s = 'SetVariables "a" "b" "c"';
>>> l = s.split('"')[1::2]; # the [1::2] is a slicing which extracts odd values
>>> print l;
['a', 'b', 'c']
>>> print l[2]; # to show you how to extract individual items from output
c

这也是比正则表达式更快的方法。通过使用timeit模块,这段代码的速度大约快了4倍:

% python timeit.py -s 'import re' 're.findall("\"([^\"]*)\"", "SetVariables \"a\" \"b\" \"c\" ")'
1000000 loops, best of 3: 2.37 usec per loop

% python timeit.py '"SetVariables \"a\" \"b\" \"c\"".split("\"")[1::2];'
1000000 loops, best of 3: 0.569 usec per loop

15

正则表达式 可以很好地完成这个任务:

import re
quoted = re.compile('"[^"]*"')
for value in quoted.findall(userInputtedText):
    print value

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接