regex 如何将某些字符括在括号中[已关闭]

bbmckpt7  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(127)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

7天前关闭。
Improve this question
我想根据关键字将某些字符括在括号中。虽然这段代码的输出是'A_B101_c1',但我想得到'(A)_(B)(101)_(c)1'

import re
text = 'A_B101_c1'
keyword = r'(A)_(B|D)([0-9]+)_([a-z])'
re.search(keyword, text).group()

字符串
我想知道如何根据任何关键字输出匹配的组和剩余的括号。那么,我如何定义这样一个函数?

def f(text, keyword):
    ???


预期输出(关键字'r'(A)_(B|D)([0-9]+)_([a-z])'):
文本:'A_B101_c1'-->输出:'(A)_(B)(101)_(c)1'
文本:'A_D1_dc'-->输出:'(A)_(D)(1)_(d)c'
预期输出(关键字'([A-Z])12(b|d)(.*)c([1-9]+)'
文本:'A12ba_Bc123'-->输出:'(A)12(b)(a_B)c(123)'

cunj1qz1

cunj1qz11#

试验项目:

import re
text ='A_B101_c1' #text = 'A_D1_dc'
keyword = r'(A)_(B|D)([0-9]+)_([a-z])'

output = re.sub(keyword, r'(\1)_(\2)(\3)_(\4)', text)
print(output)

字符串
输出量:

(A)_(B)(101)_(c)1
(A)_(D)(1)_(d)c

lkaoscv7

lkaoscv72#

可能以通用方式实现您想要的最简单方法是通过迭代使用re.search模式找到的组来构建输出字符串,对于每个组,首先添加它前面的输入文本,然后添加()中的组文本;最后添加其余的输入文本:

import re

def replace_groups(pat, text):
    res = ''
    s = 0
    match = re.search(pat, text)
    if match is None:
        return text
    for m in range(1, len(match.groups())+1):
        # ignore empty or not matched groups
        if match.start(m) == match.end(m):
            continue
        res += text[s:match.start(m)]
        res += f'({match.group(m)})'
        s = match.end(m)
    res += text[s:]
    return res

replace_groups(r'(A)_(B|D)([0-9]+)_([a-z])', 'A_B101_c1')
# '(A)_(B)(101)_(c)1'
replace_groups(r'(A)_(B|D)([0-9]+)_([a-z])', 'A_D1_dc')
# '(A)_(D)(1)_(d)c'
replace_groups(r'([A-Z])12(b|d)(.*)c([1-9]+)', 'A12ba_Bc123')
# '(A)12(b)(a_B)c(123)'
replace_groups(r'(\d+)AB(\d*)C(\d+)D([ef])', '45ABC361Df')
# '(45)ABC(361)D(f)'
replace_groups(r'(\d+)A(?:(\d+)C|([a-z])D)(\d+)', '99A3C45xy')
# '(99)A(3)C(45)xy'
replace_groups(r'(\d+)A(?:(\d+)C|([a-z])D)(\d+)', '99AqD01w')
# '(99)A(q)D(01)w'
replace_groups(r'(\d+)A(?:(\d+)C|([a-z])D)(\d+)', 'abc')
# 'abc'

字符串

相关问题