user1685095
user1685095

Reputation: 6121

Regex replace a certain word with optional commas and space around it

I have a python code that for example could look like that

class Foo(Bar, Baz, Jazz):
   pass

or that

class Foo(Baz, Bar, Jazz):
   pass

class Foo(Baz, Jazz, Bar):
   pass

What I need is to remove Bar with from the list of parents in inheritance hierarchy.

So the idea is to remove occurencies of Bar with optional , to the left or (exclusive) to right to it.

My attempt to do that with sed.

echo 'class Foo(Baz, Bar, Jazz):' | sed -r 's/(class .*\(.*)([, ]*Bar[, ]*)/\1/'

gives correct result

class Foo(Baz, Jazz):

Upvotes: 3

Views: 202

Answers (3)

riteshtch
riteshtch

Reputation: 8769

You can specify multiple expressions to satisfy different conditions like this:

$ cat a.py 
class Foo(Baz, Bar, Jazz):
   pass

class Foo(Baz, Jazz, Bar):
   pass

class Foo(Bar, Baz, Jazz):
   pass
$ sed -r -e '/^\s*class.*,\s*Bar\s*,.*$/s/,\s*Bar\s*,/,/g' -e '/^\s*class.*,\s*Bar\s*\).*$/s/,\s*Bar\s*\)/)/g' -e '/^\s*class.*\(\s*Bar\s*,\s*.*$/s/\(\s*Bar\s*,\s*/(/g' a.py 
class Foo(Baz, Jazz):
   pass

class Foo(Baz, Jazz):
   pass

class Foo(Baz, Jazz):
   pass
$

The regex also has checks that it should perform substitution on lines that satisfy class declaration in python, therefore it doesn't touches any other lines(for eg: leaves import as it is).

Upvotes: 0

sat
sat

Reputation: 14949

If I understand correctly, then this sed should do what you expect.

sed -r '/^\s*class.*:\s*$/s/(,\s*Bar\s*|\s*Bar\s*,\s*)//g' file

Output:

class Foo(Baz, Jazz):
   pass

class Foo(Baz, Jazz):
   pass

Upvotes: 1

vks
vks

Reputation: 67978

(class .*?\(.*?)(?:[\s,]+Bar\s*|\s*Bar[\s,]+)

You can use this.Replace by \1.See demo.

https://regex101.com/r/zJ7vZ4/2

import re
p = re.compile(ur'(class .*?\(.*?)(?:[\s,]+Bar\s*|\s*Bar[\s,]+)')
test_str = u"class Foo(Bar, Baz, Jazz):\n   pass\n\n\n\nclass Foo(Baz, Bar, Jazz):\n   pass\n\nclass Foo(Baz, Jazz, Bar):\n   pass"
subst = u"\1"

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

Upvotes: 0

Related Questions