-1

I have two regex strings in .net

preRegex = "(?<=(^|[^A-Za-z0-9]+))"
postRegex = "(?=([^A-Za-z0-9]+)|$)"

I want their alternative in python. My problem is let say I have a string

s="I am in aeroplane."

What I need is to replace "aeroplane with aeroPlain" so I want to make regex like

newKey = preRegex + aeroplane + postRegex
pattern = re.compile(newKey,re.IGNORECASE)

new regex string look like

(?<=(^|[^A-Za-z0-9]+))aeroplane(?=([^A-Za-z0-9]+)|$)

but it is giving me error "look-behind requires fixed-width pattern". I am new to python, Help would be appreciated. Thanks

Hassan Malik
  • 527
  • 5
  • 19

1 Answers1

0

You can use the following regex:

(^|[^A-Za-z0-9]+)aeroplane([^A-Za-z0-9]+|$)

and when you replace, you can call the back reference to the first and second part of your regex to fetch their value.

Replacement string will be something like '\1aeroPlain\2'. For more information on backref in python:https://docs.python.org/3/howto/regex.html

Good luck!

Allan
  • 11,650
  • 3
  • 27
  • 49