1

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
Denys
  • 3,927
  • 6
  • 47
  • 76

3 Answers3

1
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)
Jayanth Koushik
  • 9,006
  • 1
  • 38
  • 49
1

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.
Colin Su
  • 4,564
  • 2
  • 18
  • 19
0

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

Denys
  • 3,927
  • 6
  • 47
  • 76