Reputation: 1468
I want to replace all *
(that do not have .
before them) in my string with .*
.
Expected results -
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
Reputation: 163277
You could use a negative lookbehind (?<!\.)
to assert what is on the left is not a dot:
(?<!\.)(\*)
For example:
test_str = """foo*
foo.*
"""
result = re.sub(r"(?<!\.)(\*)", r".\1", test_str)
print (result)
Result
foo.*
foo.*
Upvotes: 2
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)
Upvotes: 2