python - Python : Convert named group to integer 中的正则表达式替换

标签 python regex

在替换字符串中的模式时,
我特别需要匹配命名组的整数/长值。

案例示例和我的尝试:

status = {1:'foo', 23:'bar'}
re.sub(
    '<status>(?P<id>\d+)',
    status.get(int(r'\g<id>')), # ValueError: invalid literal for int() with base 10: '\\g<id>'
    # status.get(int(r'\g<id>'.decode())), # ValueError: invalid literal for int() with base 10: '\\g<id>'
    # status.get('%d' % r'\g<id>'), # %d format: a number is required, not str
    'Tom ran: from <status>1 to <status>23')

普通转换适用于原始字符串 int(r'22') 但它在上面不起作用?

最佳答案

这应该适合你:

re.sub(
    '<status>(?P<id>\d+)',
    lambda m: status.get(int(m.group('id'))),
    'Tom ran: from <status>1 to <status>23')

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. @ http://docs.python.org/library/re.html#re.sub

关于python - Python : Convert named group to integer 中的正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925230/

相关文章:

python - 使用 Python 如何从 Excel 文件获取输入、定义函数并在该 Excel 文件的新工作表中生成输出?

JavaScript 正则表达式上的转义星号

php - 为什么 3 个反斜杠在 PHP 中等于 4 个反斜杠?

php - 正则表达式匹配空格但跳过部分

python - 无法在Python中导入 basemap 库

python - 按特定字段对 django 模型列表进行排序

python - 如何在python中将字符串转换为数字

python - Microsoft MSAL 是否提供资源所有者密码凭据授予授权支持?

javascript - 查找段落内元素的周围字符

regex - 如何从相反方向在R中执行模式匹配?