python - 翻译正则表达式匹配组

标签 python regex

我需要根据 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/

相关文章:

python - 为什么 3+++ 5 在 Python 中有效

python - MySQLdb._exceptions.OperationalError ('1046, No database selected' ) - Flask 到 mySQL 连接错误

c++ - 编译器能否从正则表达式中计算出 DFA?

excel - 从 VBA 中的范围中删除特殊字符

java - 正则表达式的字符串中的COLON unicode和冒号之间有区别吗?

MySQL字符串动态替换

python - Pandas groupby cumcount 从具有特定列值的行开始

python - 如何使用 tox 添加到 $PATH?

python - django-rest-framework 对字段 "required"选项的说明

java - 在Scala中使用正则表达式(字符串+数字)