Replace character with another only if repeated and not part of a wordOnly match word outside a HTML statement with a regex“ReplaceWith” & - but only part of itRegExp regular expression find & replace whole words onlyJava regex - parts of wordsRegex match word groups and parts of previously matched word groupsWord replacement using regex if the target word is not a part of another wordreplace after “word” character by character in notepad ++?Why does `word (.(?!another-word))*?` match only a character?Replacing consecutive repeated characters in javareplacing part of a string but the part is very long

How do I rename a Linux host without needing to reboot for the rename to take effect?

A Rare Riley Riddle

How do scammers retract money, while you can’t?

Is there a problem with hiding "forgot password" until it's needed?

How do I extract a value from a time formatted value in excel?

Go Pregnant or Go Home

Failed to fetch jessie backports repository

How does buying out courses with grant money work?

How does it work when somebody invests in my business?

How to check is there any negative term in a large list?

What is the intuitive meaning of having a linear relationship between the logs of two variables?

Is a stroke of luck acceptable after a series of unfavorable events?

How can I kill an app using Terminal?

How can a function with a hole (removable discontinuity) equal a function with no hole?

Class Action - which options I have?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

What can we do to stop prior company from asking us questions?

Applicability of Single Responsibility Principle

Term for the "extreme-extension" version of a straw man fallacy?

What is the difference between "behavior" and "behaviour"?

Do the temporary hit points from the Battlerager barbarian's Reckless Abandon stack if I make multiple attacks on my turn?

Short story about space worker geeks who zone out by 'listening' to radiation from stars

System.debug(JSON.Serialize(o)) Not longer shows full string

Increase performance creating Mandelbrot set in python



Replace character with another only if repeated and not part of a word


Only match word outside a HTML statement with a regex“ReplaceWith” & - but only part of itRegExp regular expression find & replace whole words onlyJava regex - parts of wordsRegex match word groups and parts of previously matched word groupsWord replacement using regex if the target word is not a part of another wordreplace after “word” character by character in notepad ++?Why does `word (.(?!another-word))*?` match only a character?Replacing consecutive repeated characters in javareplacing part of a string but the part is very long













6















In Python3, the following code works to replace a string (two or more) of *'s with x's.



import re
re.sub(r'*(?=*)|(?<=*)*', 'x', 'Replace this *** but not this *')
# 'Replace this xxx but not this *'


But what if I also want to exempt a string of *'s that are part of a "word" like the following? (I.e. the string is attached to one or more [a-zA-Z] characters.)



text = "Don't replace foo*** or **bar, either."
# unmodified text expected


How do I do this? I can probably match the exempted cases as well and use a replacement function to deal with them, but is there a better way?










share|improve this question




























    6















    In Python3, the following code works to replace a string (two or more) of *'s with x's.



    import re
    re.sub(r'*(?=*)|(?<=*)*', 'x', 'Replace this *** but not this *')
    # 'Replace this xxx but not this *'


    But what if I also want to exempt a string of *'s that are part of a "word" like the following? (I.e. the string is attached to one or more [a-zA-Z] characters.)



    text = "Don't replace foo*** or **bar, either."
    # unmodified text expected


    How do I do this? I can probably match the exempted cases as well and use a replacement function to deal with them, but is there a better way?










    share|improve this question


























      6












      6








      6








      In Python3, the following code works to replace a string (two or more) of *'s with x's.



      import re
      re.sub(r'*(?=*)|(?<=*)*', 'x', 'Replace this *** but not this *')
      # 'Replace this xxx but not this *'


      But what if I also want to exempt a string of *'s that are part of a "word" like the following? (I.e. the string is attached to one or more [a-zA-Z] characters.)



      text = "Don't replace foo*** or **bar, either."
      # unmodified text expected


      How do I do this? I can probably match the exempted cases as well and use a replacement function to deal with them, but is there a better way?










      share|improve this question
















      In Python3, the following code works to replace a string (two or more) of *'s with x's.



      import re
      re.sub(r'*(?=*)|(?<=*)*', 'x', 'Replace this *** but not this *')
      # 'Replace this xxx but not this *'


      But what if I also want to exempt a string of *'s that are part of a "word" like the following? (I.e. the string is attached to one or more [a-zA-Z] characters.)



      text = "Don't replace foo*** or **bar, either."
      # unmodified text expected


      How do I do this? I can probably match the exempted cases as well and use a replacement function to deal with them, but is there a better way?







      python regex python-3.x






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 3 hours ago









      0m3r

      8,02292554




      8,02292554










      asked 3 hours ago









      bongbangbongbang

      607720




      607720






















          2 Answers
          2






          active

          oldest

          votes


















          7














          regex = r"s*2,[sn]"


          This matches 2 or more * chars, surrounded by whitespace (or ended with a newline)



          Call it maybe like this?



          regex = r"s*2,[sn]"


          def replacer(match):
          return 'x' * len(match.group())

          re.sub(regex, replacer, your_string_here)





          share|improve this answer























          • You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

            – bongbang
            3 hours ago



















          0














          This answer is inspired Danielle M.'s. This pattern below seems to give me what I want. The rest is the same as hers.



          regex = r'(?<![a-zA-Z])*2,(?![a-zA-Z])'





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389122%2freplace-character-with-another-only-if-repeated-and-not-part-of-a-word%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            7














            regex = r"s*2,[sn]"


            This matches 2 or more * chars, surrounded by whitespace (or ended with a newline)



            Call it maybe like this?



            regex = r"s*2,[sn]"


            def replacer(match):
            return 'x' * len(match.group())

            re.sub(regex, replacer, your_string_here)





            share|improve this answer























            • You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

              – bongbang
              3 hours ago
















            7














            regex = r"s*2,[sn]"


            This matches 2 or more * chars, surrounded by whitespace (or ended with a newline)



            Call it maybe like this?



            regex = r"s*2,[sn]"


            def replacer(match):
            return 'x' * len(match.group())

            re.sub(regex, replacer, your_string_here)





            share|improve this answer























            • You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

              – bongbang
              3 hours ago














            7












            7








            7







            regex = r"s*2,[sn]"


            This matches 2 or more * chars, surrounded by whitespace (or ended with a newline)



            Call it maybe like this?



            regex = r"s*2,[sn]"


            def replacer(match):
            return 'x' * len(match.group())

            re.sub(regex, replacer, your_string_here)





            share|improve this answer













            regex = r"s*2,[sn]"


            This matches 2 or more * chars, surrounded by whitespace (or ended with a newline)



            Call it maybe like this?



            regex = r"s*2,[sn]"


            def replacer(match):
            return 'x' * len(match.group())

            re.sub(regex, replacer, your_string_here)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 3 hours ago









            Danielle M.Danielle M.

            2,2051623




            2,2051623












            • You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

              – bongbang
              3 hours ago


















            • You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

              – bongbang
              3 hours ago

















            You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

            – bongbang
            3 hours ago






            You gave me a good idea for the use of the replacer function, but your pattern, by including the spaces in the match, would seem to turn this **** string into this******string, which is not I want. It would also not replace **** this string, which I do want to replace. That said, I now have a solution that works thanks to you. Thank you.

            – bongbang
            3 hours ago














            0














            This answer is inspired Danielle M.'s. This pattern below seems to give me what I want. The rest is the same as hers.



            regex = r'(?<![a-zA-Z])*2,(?![a-zA-Z])'





            share|improve this answer



























              0














              This answer is inspired Danielle M.'s. This pattern below seems to give me what I want. The rest is the same as hers.



              regex = r'(?<![a-zA-Z])*2,(?![a-zA-Z])'





              share|improve this answer

























                0












                0








                0







                This answer is inspired Danielle M.'s. This pattern below seems to give me what I want. The rest is the same as hers.



                regex = r'(?<![a-zA-Z])*2,(?![a-zA-Z])'





                share|improve this answer













                This answer is inspired Danielle M.'s. This pattern below seems to give me what I want. The rest is the same as hers.



                regex = r'(?<![a-zA-Z])*2,(?![a-zA-Z])'






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 3 hours ago









                bongbangbongbang

                607720




                607720



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389122%2freplace-character-with-another-only-if-repeated-and-not-part-of-a-word%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                    Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                    Category:Tremithousa Media in category "Tremithousa"Navigation menuUpload media34° 49′ 02.7″ N, 32° 26′ 37.32″ EOpenStreetMapGoogle EarthProximityramaReasonatorScholiaStatisticsWikiShootMe