如何批量替换特定范围…. u010045303 已结题采纳率0% 2019-02-08 如何批量替换特定范围内的指定字符串?(正则表达式, notepad + + Xml )

问题:有若干 xml 文件,每个 xml 文件内有如下类似字段:
id=@a b c {e f g}

id=@f g ht {it et g} ##需求: 需要批量将 与 之间的所有的“空格”改为“_”, 空格以外的部分保持不变。引号中所有的空格改为“_”,其余部分保持不变(据说nodepad正则表达式可以实现,但我不怎么会,求各位老板支个招)

是要将{与}之间的所有的“空格”改为“_”?
notepad++中正则表达式做不到这个要求, 可以用python代码来做

你题目的解答代码如下:

import re
s = '''
id=@a b c {e f g}
id=@f g ht {it et g}
'''
s = re.sub(r'\{.*?\}',lambda x: re.sub(r' ',r'_',x.group(0)),s)
print(s)

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

import re
import os

text = '''
id=@a b c {e f g}
id=@f g ht {it et g}
'''

pattern = '\{(.+?)\}'
result_dir = './result'

if not os.path.exists(result_dir):
    os.mkdir(result_dir)

for p, d, f in os.walk('.'):
    for file in f:
        if file.endswith('.xml'):
            print(f'solving {file}...')
            with open(os.path.join(p, file), 'r') as ori:
                text = ori.read()
                text = re.sub(pattern, lambda x: re.sub(
                    ' ', '_', x.group(0)), text)
                with open(os.path.join(result_dir, file), 'w+') as output:
                    output.write(text)

放在待处理的文件夹内运行,会在该目录下生成一个result文件夹,里面是批量处理后的结果

img

有帮助望采纳~

img

notepad CTRL+F替换,查找模式选择正则
查找目标:\b\s+\b(?=\S[^{]*})
替换为:_
全部替换