-2

I have a python variable (type unicode), which holds a query statement:

CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));

I need to replace all the values in each VARCHAR occurence with 254. Initially I thought it would be enough to use the replace() function but this won't work as the numbers in the parenthesis are random.

Is there a way to do this using regex?

user1919
  • 3,818
  • 17
  • 62
  • 97
  • 1
    So, have you tried anything yet? Looks like a straight-forward task. [Matching parentheses with a regex](http://stackoverflow.com/questions/5302942/matching-parentheses-in-python-regular-expression) is a solved issue. – Wiktor Stribiżew Sep 14 '16 at 12:06

2 Answers2

4

with regexp:

import re
query = 'CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));'
print re.sub(r'VARCHAR\([0-9]*\)','VARCHAR(254)',query)
Laurens Koppenol
  • 2,946
  • 2
  • 20
  • 33
1
import re

s='''CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));'''
re.sub('VARCHAR\([0-9]{1,3}\)','VARCHAR(254)',s)

There are plenty of other solutions and you don't even need python for this. The easiest would be to use sed.

e4c5
  • 52,766
  • 11
  • 101
  • 134