How to remove text after and before certain words in a string using python regex

I have the line "copy table a (no = 1, name = xyz, city = c0nl) from 'a.dat';". In this I want to delete the words in 'copy' and 'from', but I need a file name like: my desired result: "copy a from a.dat;"

Any help would be great. I want to use a regular expression for this.

+4
source share
3 answers

You can use the regex module reand the function sub(replace / replace) in combination with lookahead (?=from)and lookbehind (?<=copy )- also called lookaround , to remove only the requested part (.*)that is between them:

import re
print re.sub(r'(?<=copy )(.*)(?=from)', '', "copy table values from 'a.dat';")

OUTPUT

copy from 'a.dat';
+5
source
(?<=\bcopy\b)[\s\S]*?(?=\s*\bfrom\b)

Use \band lookarounds. See the demo.

https://regex101.com/r/sS2dM8/11

import re
p = re.compile(r'(?<=\bcopy\b)[\s\S]*?(?=\s*\bfrom\b)', re.MULTILINE)
test_str = "copy table values from 'a.dat';"
subst = ""

result = re.sub(p, subst, test_str)

Exit: copy from 'a.dat';

0
source

You can do:

import re
mystr = "copy table values from 'a.dat';"
print(re.sub('copy.*from', 'copy from', mystr))

And you do not worry about spaces, greed and all this.

0
source

All Articles