-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
  • 559
  • 6
  • 20
  • As the question stands, I'm not sure what the objective is. It may be helpful to include .NET code that has the working regular expression. It may also be helpful to include the generalized objective. E.g. "looking to replace all instances of aeroplane with aeroPlain in a string". – Arbiter of buffoonery Dec 07 '17 at 07:10
  • The error is crystal clear: `Python lookbehind assertions need to be fixed width`, on top of this in your current example your pattern is at the end of the string so you could replace it by `(?=\.|$)` – Allan Dec 07 '17 at 07:11
  • How to handle this situation? when i have not fixed width? – Hassan Malik Dec 07 '17 at 07:12
  • 1
    Correct is `preRegex = "(?<![A-Za-z0-9])"` and `postRegex = "(?![A-Za-z0-9])"` – Wiktor Stribiżew Dec 07 '17 at 07:25

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
  • 12,117
  • 3
  • 27
  • 51