Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-提取子字符串列表_Python_Regex - Fatal编程技术网

Python-提取子字符串列表

Python-提取子字符串列表,python,regex,Python,Regex,如何基于python中的某些模式提取子字符串列表 比如说, str = 'this {{is}} a sample {{text}}'. 预期结果:包含“is”和“text”的python列表您可以使用正则表达式匹配{{和}之间发生的任何内容。那对你有用吗 一般来说,对于在大量文本中标记某些字符串,a将非常有用。您可以使用以下选项: >>> import re >>> re.findall("{{(.*?)}}", "this {{is}} a sample

如何基于python中的某些模式提取子字符串列表

比如说,

str = 'this {{is}} a sample {{text}}'.

预期结果:包含“is”和“text”的python列表

您可以使用正则表达式匹配
{{
}
之间发生的任何内容。那对你有用吗


一般来说,对于在大量文本中标记某些字符串,a将非常有用。

您可以使用以下选项:

>>> import re
>>> re.findall("{{(.*?)}}", "this {{is}} a sample {{text}}")
['is', 'text']
res = re.findall("{{([^{}]*)}}", a)
print "a python list which contains %s and %s" % (res[0], res[1])
欢呼声

假设“某些模式”的意思是“两个{}之间的单个单词”:

进口稀土

re.findall('{(\w*)}}',字符串)


编辑:Andrew Clark的答案实现了“双精度{}之间的任何字符序列”

对于您的示例来说,基于正则表达式的解决方案很好,不过我建议对更复杂的输入使用更健壮的方法

import re

def match_substrings(s):
    return re.findall(r"{{([^}]*)}}", s)
由内而外的正则表达式:

[^}]
匹配任何不是“}”的内容
([^}]*)
匹配任意数量的非}字符并将其分组
{([^}]*)}
将上述内容放在双括号内


如果没有上面的括号,
re.findall
将返回整个匹配项(即
[{{is}}',{{text}}]
。但是,当正则表达式包含一个组时,findall将使用该组。

是否仅提取出现在双大括号中的子字符串?@Rafe是的。我只需要大括号中的字符串。通常命名变量
string
不是一个好主意,因为它是一个常用的Python模块。您必须使用 %r而不是
%s
否则您将无法获得引号;)谢谢,我不知道这一点。例如,我通常会将格式(“”)放在打印字符串本身(“%s”)中。Cheers@Siva:您需要对[s进行转义,因为它们在正则表达式中有一个含义:
re.findall(r“\\[\\[(.*)]”),“this[[is]]a sample[[text].”