Skip to main content
 首页 » 编程设计

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

2024年10月24日23傻小

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

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对于数字,当您事先知道内容将包含什么时。