Denys
Denys

Reputation: 4557

Replace part of the string matching the pattern

It's my first Python day, so please excuse me for this question

The Problem: in a file replace every occurrence of trim(column_name) with 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.

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

Upvotes: 1

Views: 164

Answers (3)

Denys
Denys

Reputation: 4557

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

Upvotes: 0

Colin Su
Colin Su

Reputation: 4619

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_].
  2. \(\) means the normal parenthesis, () means the grouping
  3. use \1 to render the first match group, \2 for second one.

Upvotes: 1

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

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)

Upvotes: 1

Related Questions