Extract string from between quotations

▼魔方 西西 提交于 2019-12-18 11:03:30

问题


I want to extract information from user-inputted text. Imagine I input the following:

SetVariables "a" "b" "c"

How would I extract information between the first set of quotations? Then the second? Then the third?


回答1:


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



回答2:


You could do a string.split() on it. If the string is formatted properly with the quotation marks (i.e. even number of quotation marks), every odd value in the list will contain an element that is between quotation marks.

>>> 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

This is also a faster approach than regular expressions. With the timeit module, the speed of this code is around 4 times faster:

% 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



回答3:


Regular expressions are good at this:

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


来源:https://stackoverflow.com/questions/2076343/extract-string-from-between-quotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!