我需要根据 pdf 文件规范来匹配名称对象。但是,名称可以包含十六进制数字(前面带有#)来指定特殊字符。我想将这些匹配翻译为相应的字符。有没有一种聪明的方法可以在不重新解析匹配字符串的情况下做到这一点?
import re
Name = re.compile(r'''
(/ # Literal "/"
(?: #
(?:\#[A-Fa-f0-9]{2}) # Hex numbers
| #
[^\x00-\x20 \x23 \x2f \x7e-\xff] # Other
)+ #
) #
''', re.VERBOSE)
# some examples
names = """
The following are examples of valid literal names:
Raw string Translation
1. /Adobe#20Green -> "Adobe Green"
2. /PANTONE#205757#20CV -> "PANTONE 5757 CV"
3. /paired#28#29parentheses -> "paired( )parentheses"
4. /The_Key_of_F#23_Minor -> "The_Key_of_F#_Minor"
5. /A#42 -> "AB"
6. /Name1
7. /ASomewhatLongerName
8. /A;Name_With-Various***Characters?
9. /1.2
10. /$$
11. /@pattern
12. /.notdef
"""
最佳答案
我将 finditer()
与包装器生成器一起使用:
import re
from functools import partial
def _hexrepl(match):
return chr(int(match.group(1), 16))
unescape = partial(re.compile(r'#([0-9A-F]{2})').sub, _hexrepl)
def pdfnames(inputtext):
for match in Name.finditer(inputtext):
yield unescape(match.group(0))
演示:
>>> for name in pdfnames(names):
... print name
...
/Adobe Green
/PANTONE 5757 CV
/paired()parentheses
/The_Key_of_F#_Minor
/AB
/Name1
/ASomewhatLongerName
/A;Name_With-Various***Characters?
/1.2
/$$
/@pattern
/.notdef
据我所知,没有比这更聪明的方法了; re
引擎无法以其他方式将替换和匹配结合起来。
关于python - 翻译正则表达式匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17144809/