从引用之间提取字符串

Rez*_*nor 25 python string extraction quotations

我想从用户输入的文本中提取信息.想象一下,我输入以下内容:

SetVariables "a" "b" "c"
Run Code Online (Sandbox Code Playgroud)

如何在第一组报价之间提取信息?然后第二个?然后第三个?

jsp*_*cal 42

>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

  • 行尾是否需要分号? (2认同)

Rom*_*man 30

你可以在上面做一个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
Run Code Online (Sandbox Code Playgroud)

这也是比正则表达式更快的方法.使用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
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 12

正则表达式很擅长:

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