Barun Sharma
Barun Sharma

Reputation: 1468

Negative regex matching

I want to replace all *(that do not have . before them) in my string with .*.

Expected results -

  1. foo* --> foo.*
  2. foo.* --> foo.*

I tried re.sub("(?!\.)\*", ".*", "foo*") to replace all such occurrences, but this does not seem to work.

>>> re.sub("(?!\.)\*", ".*", "foo.*")
   'foo..*'

Any help on what am I missing here?

Upvotes: 1

Views: 45

Answers (3)

The fourth bird
The fourth bird

Reputation: 163277

You could use a negative lookbehind (?<!\.) to assert what is on the left is not a dot:

(?<!\.)(\*)

Regex demo

For example:

test_str = """foo*
foo.*
"""
result = re.sub(r"(?<!\.)(\*)", r".\1", test_str)
print (result)

Result

foo.*
foo.*

Upvotes: 2

Sandro Schaurer
Sandro Schaurer

Reputation: 417

Have you tried to do it like this:

[^\.]\*

Upvotes: 0

Jan
Jan

Reputation: 43169

You were using a neg. lookahead ((?!...)), not a lookbehind ((?<!...)), see

import re

string = """
foo* --> foo.*
foo.* --> foo.*
"""

rx = re.compile(r'(?<!\.)\*')

string = rx.sub('.*', string)
print(string)

And a demo on regex101.com.

Upvotes: 2

Related Questions