简体   繁体   English

替换与模式匹配的部分字符串

[英]Replace part of the string matching the pattern

It's my first Python day, so please excuse me for this question 这是我的第一个Python天,请原谅我这个问题

The Problem: in a file replace every occurrence of trim(column_name) with TRIM (TRIM (CHR (09) FROM column_name)) . 问题:在文件中,将每次出现的trim(column_name)替换为TRIM(TRIM(CHR(09)FROM column_name)) I've already sorted out how to do a pattern search and acquainted myself with the re.sub() function. 我已经弄清楚了如何进行模式搜索,并熟悉了re.sub()函数。

the pattern that matches my case is 与我的情况相符的模式是

p = re.compile ('trim\([a-z0-9_]+\)',re.I)

but how do I replace the matching pattern preserving the column name??? 但是如何替换保留列名称的匹配模式呢???

The needed output is, for example, as follows: 所需的输出例如如下:

input: select trim(API12), trim(FIELD_CODE) from table
output: select TRIM (TRIM (CHR (09) FROM API12)), TRIM (TRIM (CHR (09) FROM FIELD_CODE)) from table
import re
s = 'select trim(API12), trim(FIELD_CODE) from table'
print re.sub(r'trim\((?P<col>[a-zA-Z0-9_]+)\)', 'TRIM (TRIM (CHR (09) FROM \g<col>))', s)

Working code: 工作代码:

import re
i = 'select trim(API12), trim(FIELD_CODE) from table'
re.sub(r"trim\((\w+)\)", r"TRIM (TRIM (CHR (09) FROM \1))", i)

Explain 说明

  1. You don't have to use flag re.I , use \\w instead, it's equivalence to [a-zA-Z0-9_] . 您不必使用标志re.I ,而是使用\\w ,它等效于[a-zA-Z0-9_]
  2. \\(\\) means the normal parenthesis, () means the grouping \\(\\)表示普通括号, ()表示分组
  3. use \\1 to render the first match group, \\2 for second one. 使用\\1以使第一匹配组, \\2为第二个。

I've just sorted this one out for myself 我刚刚为自己整理了一个

Thanks for your help! 谢谢你的帮助!

import re

line = "select trim(API12), trim(FIELD_CODE) from dual"

output = re.sub(r'trim\(([a-zA-Z0-9_]+)\)',r'TRIM (TRIM (CHR (09) FROM\1))',line)

print output

>> select TRIM (TRIM (CHR (09) FROM API12)), TRIM (TRIM (CHR (09) FROM FIELD_CODE)) from dual >>从双中选择TRIM(TRIM(来自API12的CHR(09)),TRIM(TRIM(来自FIELD_CODE的CHR(09)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM