omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Python question about case insensitive replacement

    Pythonista
    3
    4
    2134
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • cvp
      cvp last edited by

      I've a text 'Word word'
      How can I replace the string 'word' independantly of its case by itself followed by a another string, exemple 'xxx'
      Thus my text should become 'Wordxxx wordxxx'.

      If I use

      		import re
      		my_text = 'Word word'
      		src_str  = re.compile('word', re.IGNORECASE) 
      		my_text = src_str.sub('wordxxx', my_text)
      

      Result will be 'wordxxx wordxxx', thus I lose original case

      I know I could loop on occurrences but if you know an easier way...

      1 Reply Last reply Reply Quote 0
      • Olaf
        Olaf last edited by

        You can use \1 to refer to matched text grouped by () in the regex. So:

        import re
        my_text = 'Word word'
        src_str  = re.compile('(word)', re.IGNORECASE) 
        my_text = src_str.sub(r'\1xxx', my_text)
        print(my_text)
        cvp 1 Reply Last reply Reply Quote 3
        • cvp
          cvp @Olaf last edited by

          @Olaf Thanks a lot, I didn't know this \1

          1 Reply Last reply Reply Quote 0
          • JanRomero
            JanRomero last edited by JanRomero

            This post is deleted!
            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors