Replacing unquoted words only in Python

后端 未结 6 852
情深已故
情深已故 2021-01-21 04:03

I am looking for a way to replace a word, however only when its not surounded by quotations.

For example Replacing Hello with Hi

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 04:43

    Using regular expressions:

    >>> import re
    >>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "Hello mate")
    'Hi mate'
    >>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "'Hello' mate")
    "'Hello' mate"
    

    '([^"\']|^)Hello([^"\']|$)' means 'The string Hello surrounded by something different than a single or double quote, or at the beginning or end of the line'.

提交回复
热议问题