discared
discared

Reputation: 19

regex produces not what I need

Re.sub replaces text with parentheses The code:

import re

print(re.sub(r'sizeOfWindow\b[^.]','x234234','sizeOfWindow.(sizeOfWindow)'))

I want sizeOfWindow. (X234234) , but it prints sizeOfWindow. (X234234 What's wrong with my regex?

Upvotes: 0

Views: 45

Answers (2)

The fourth bird
The fourth bird

Reputation: 163467

As per the comment

I need re.sub to replace a certain word that does not end with a dot

This part [^.] is a negated character class that matches a single char other than a dot, that is why it matches the parenthesis and is it gone after the replacement.

You can use a negative lookahead instead asserting not a dot directly to the right.

import re
 
print(re.sub(r'sizeOfWindow\b(?!\.)','x234234','sizeOfWindow.(sizeOfWindow)'))

Output

sizeOfWindow.(x234234)

See a Python demo

Upvotes: 2

Rolv Apneseth
Rolv Apneseth

Reputation: 2118

Edited based on your comments and based on fourth birds regex in the comments, but using a negative lookahead instead:

print(re.sub(r'sizeOfWindow(?![.])','x234234','sizeOfWindow.(sizeOfWindow)'))

This should match the word, if it is not immediately followed by .

Upvotes: 0

Related Questions