搜索嵌入在{}after关键字中的字符串

2024-05-04 05:09:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

includegraphics[x=2]{image.pdf}

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


Tags: 字符串image文本内容pdf图片关键字大括号
2条回答

使用re.search

re.search(r'includegraphics\[[^\[\]]*\]\{([^}]*)\}', s).group(1)

使用re.findall

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

解释:

^{} module处理Python中的正则表达式。它的^{}方法可用于查找字符串中模式的所有出现处。你知道吗

您感兴趣的模式的正则表达式是'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表示数字,前提是您事先知道内容将由什么组成。你知道吗

相关问题 更多 >