gpt4 book ai didi

python - 在关键字后搜索嵌入在 {} 中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:32 29 4
gpt4 key购买 nike

如何获取关键字后嵌入 {} 中的字符串,其中关键字和大括号 {} 之间的字符数未知。 例如:

includegraphics[x=2]{image.pdf}

关键字将是 includegraphics,要查找的字符串是 image.pdf,但 [x=2] 之间的文本可以是两者之间的任何内容 []。所以我想忽略关键字和 { 之间的所有字符,或者我想忽略 []

之间的所有字符

最佳答案

使用 re.findall

>>> sample = 'includegraphics[x=2]{image.pdf}'
>>> re.findall('includegraphics.*?{(.*?)}',sample)
['image.pdf']

解释:

re module处理 Python 中的正则表达式。它的 findall 方法可用于查找字符串中所有出现的模式。

您感兴趣的模式的正则表达式是 'includegraphics.*?{(.*?)}' .这里.表示“任何字符”,而 *表示0次或多次。问号使这是一个非贪婪的操作。来自文档:

The *, +, and ? qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against <H1\>title</H1>, it will match the entire string, and not just <H1>. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only <H1>.

请注意,在您的情况下使用 .*?应该没问题,通常最好使用更专业的字符组,例如 \w对于字母数字和 \d对于数字,当您事先知道内容将包含什么时。

关于python - 在关键字后搜索嵌入在 {} 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837330/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com