Regex Replace seems to replace only first occurrenceMatch all occurrences of a regexA comprehensive regex for...

Equivalent of "illegal" for violating civil law

Why do neural networks need so many training examples to perform?

What makes papers publishable in top-tier journals?

A Missing Symbol for This Logo

Is there a verb that means to inject with poison?

Count repetitions of an array

Non-Cancer terminal illness that can affect young (age 10-13) girls?

Why do we have to make "peinlich" start with a capital letter and also end with -s in this sentence?

What is the wife of a henpecked husband called?

How to deal with possible delayed baggage?

Does a paladin have to announce that they're using Divine Smite before attacking?

What species should be used for storage of human minds?

Which RAF squadrons and aircraft types took part in the bombing of Berlin on the 25th of August 1940?

How to delete duplicate text from a file?

Why do all the books in Game of Thrones library have their covers facing the back of the shelf?

What game did these black and yellow dice come from?

Am I correct in stating that the study of topology is purely theoretical?

How can I play a serial killer in a party of good PCs?

Is there any danger of my neighbor having my wife's signature?

Why is a temp table a more efficient solution to the Halloween Problem than an eager spool?

If angels and devils are the same species, why would their mortal offspring appear physically different?

Why did the villain in the first Men in Black movie care about Earth's Cockroaches?

How to access internet and run apt-get through a middle server?

When obtaining gender reassignment/plastic surgery overseas, is an emergency travel document required to return home?



Regex Replace seems to replace only first occurrence


Match all occurrences of a regexA comprehensive regex for phone number validationHow to replace all occurrences of a string in JavaScriptHow to RegEx Replace named groupsRegEx match open tags except XHTML self-contained tagsRegex: matching up to the first occurrence of a characterRegex replace matched and remove not matchedJavaScript RegEx - replace first and last occurrence of a characterRegex for replacing first 5 numbers, irrespective of anything between them?Replace all occurrences of a white space from string except the first occurrence using Regex in C#













6















I have a string, from which I want to remove the whitespaces between the numbers:



string test = "Some Words 1 2 3 4";
string result = Regex.Replace(test, @"(d)s(d)", @"$1$2");


the expected/desired result would be:



"Some Words 1234"


but I retrieve the following:



"Some Words 12 34"


What am I doing wrong here?



Further examples:



Input:  "Some Words That Should not be replaced 12 9 123 4 12"
Output: "Some Words That Should not be replaced 129123412"

Input: "test 9 8"
Output: "test 98"

Input: "t e s t 9 8"
Output: "t e s t 98"

Input: "Another 12 000"
Output: "Another 12000"









share|improve this question





























    6















    I have a string, from which I want to remove the whitespaces between the numbers:



    string test = "Some Words 1 2 3 4";
    string result = Regex.Replace(test, @"(d)s(d)", @"$1$2");


    the expected/desired result would be:



    "Some Words 1234"


    but I retrieve the following:



    "Some Words 12 34"


    What am I doing wrong here?



    Further examples:



    Input:  "Some Words That Should not be replaced 12 9 123 4 12"
    Output: "Some Words That Should not be replaced 129123412"

    Input: "test 9 8"
    Output: "test 98"

    Input: "t e s t 9 8"
    Output: "t e s t 98"

    Input: "Another 12 000"
    Output: "Another 12000"









    share|improve this question



























      6












      6








      6








      I have a string, from which I want to remove the whitespaces between the numbers:



      string test = "Some Words 1 2 3 4";
      string result = Regex.Replace(test, @"(d)s(d)", @"$1$2");


      the expected/desired result would be:



      "Some Words 1234"


      but I retrieve the following:



      "Some Words 12 34"


      What am I doing wrong here?



      Further examples:



      Input:  "Some Words That Should not be replaced 12 9 123 4 12"
      Output: "Some Words That Should not be replaced 129123412"

      Input: "test 9 8"
      Output: "test 98"

      Input: "t e s t 9 8"
      Output: "t e s t 98"

      Input: "Another 12 000"
      Output: "Another 12000"









      share|improve this question
















      I have a string, from which I want to remove the whitespaces between the numbers:



      string test = "Some Words 1 2 3 4";
      string result = Regex.Replace(test, @"(d)s(d)", @"$1$2");


      the expected/desired result would be:



      "Some Words 1234"


      but I retrieve the following:



      "Some Words 12 34"


      What am I doing wrong here?



      Further examples:



      Input:  "Some Words That Should not be replaced 12 9 123 4 12"
      Output: "Some Words That Should not be replaced 129123412"

      Input: "test 9 8"
      Output: "test 98"

      Input: "t e s t 9 8"
      Output: "t e s t 98"

      Input: "Another 12 000"
      Output: "Another 12000"






      c# regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      DMA

      557




      557










      asked 2 hours ago









      nntynnty

      665




      665
























          2 Answers
          2






          active

          oldest

          votes


















          8














          Regex.Replace continues to search after the previous match:



          Some Words 1 2 3 4
          ^^^
          first match, replace by "12"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^^
          next match, replace by "34"


          You can use a zero-width positive lookahead assertion to avoid that:



          string result = Regex.Replace(test, @"(d)s(?=d)", @"$1");


          Now the final digit is not part of the match:



          Some Words 1 2 3 4
          ^^?
          first match, replace by "1"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^?
          next match, replace by "2"

          ...





          share|improve this answer


























          • Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

            – DMA
            2 hours ago











          • Thank you for the detailed explanation !

            – nnty
            2 hours ago



















          9














          Your regex consumes the digit on the right. (d)s(d) matches and captures 1 in Some Words 1 2 3 4 into Group 1, then matches 1 whitespace, and then matches and consumes (i.e. adds to the match value and advances the regex index) 2. Then, the regex engine tries to find another match from the current index, that is already after 1 2. So, the regex does not match 2 3, but finds 3 4.



          Here is your regex demo and a diagram showing that:



          enter image description here



          Also, see the process of matching here:



          enter image description here



          Use lookarounds instead that are non-consuming:



          (?<=d)s+(?=d)


          See the regex demo



          enter image description here



          Details





          • (?<=d) - a positive lookbehind that matches a location in string immediately preceded with a digit


          • s+ - 1+ whitespaces


          • (?=d) - a positive lookahead that matches a location in string immediately followed with a digit.


          C# demo:



          string test = "Some Words 1 2 3 4";
          string result = Regex.Replace(test, @"(?<=d)s+(?=d)", "");


          See the online demo:



          var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
          foreach (var test in strs)
          {
          Console.WriteLine(Regex.Replace(test, @"(?<=d)s+(?=d)", ""));
          }


          Output:



          Some Words 1234
          Some Words That Should not be replaced 129123412
          test 98
          t e s t 98
          Another 12000





          share|improve this answer


























          • Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

            – nnty
            2 hours ago











          • @nnty Ok, just in case, I added diagrams.

            – Wiktor Stribiżew
            1 hour ago











          • @nnty I hope the animation showing how your regex works is fine.

            – Wiktor Stribiżew
            52 mins ago











          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%2f54883163%2fregex-replace-seems-to-replace-only-first-occurrence%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









          8














          Regex.Replace continues to search after the previous match:



          Some Words 1 2 3 4
          ^^^
          first match, replace by "12"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^^
          next match, replace by "34"


          You can use a zero-width positive lookahead assertion to avoid that:



          string result = Regex.Replace(test, @"(d)s(?=d)", @"$1");


          Now the final digit is not part of the match:



          Some Words 1 2 3 4
          ^^?
          first match, replace by "1"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^?
          next match, replace by "2"

          ...





          share|improve this answer


























          • Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

            – DMA
            2 hours ago











          • Thank you for the detailed explanation !

            – nnty
            2 hours ago
















          8














          Regex.Replace continues to search after the previous match:



          Some Words 1 2 3 4
          ^^^
          first match, replace by "12"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^^
          next match, replace by "34"


          You can use a zero-width positive lookahead assertion to avoid that:



          string result = Regex.Replace(test, @"(d)s(?=d)", @"$1");


          Now the final digit is not part of the match:



          Some Words 1 2 3 4
          ^^?
          first match, replace by "1"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^?
          next match, replace by "2"

          ...





          share|improve this answer


























          • Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

            – DMA
            2 hours ago











          • Thank you for the detailed explanation !

            – nnty
            2 hours ago














          8












          8








          8







          Regex.Replace continues to search after the previous match:



          Some Words 1 2 3 4
          ^^^
          first match, replace by "12"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^^
          next match, replace by "34"


          You can use a zero-width positive lookahead assertion to avoid that:



          string result = Regex.Replace(test, @"(d)s(?=d)", @"$1");


          Now the final digit is not part of the match:



          Some Words 1 2 3 4
          ^^?
          first match, replace by "1"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^?
          next match, replace by "2"

          ...





          share|improve this answer















          Regex.Replace continues to search after the previous match:



          Some Words 1 2 3 4
          ^^^
          first match, replace by "12"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^^
          next match, replace by "34"


          You can use a zero-width positive lookahead assertion to avoid that:



          string result = Regex.Replace(test, @"(d)s(?=d)", @"$1");


          Now the final digit is not part of the match:



          Some Words 1 2 3 4
          ^^?
          first match, replace by "1"

          Some Words 12 3 4
          ^
          +-- continue searching here

          Some Words 12 3 4
          ^^?
          next match, replace by "2"

          ...






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 hours ago

























          answered 2 hours ago









          HeinziHeinzi

          123k38271408




          123k38271408













          • Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

            – DMA
            2 hours ago











          • Thank you for the detailed explanation !

            – nnty
            2 hours ago



















          • Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

            – DMA
            2 hours ago











          • Thank you for the detailed explanation !

            – nnty
            2 hours ago

















          Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

          – DMA
          2 hours ago





          Wanted to explain, but it wasn't easy. Yours were the best explanation 👍

          – DMA
          2 hours ago













          Thank you for the detailed explanation !

          – nnty
          2 hours ago





          Thank you for the detailed explanation !

          – nnty
          2 hours ago













          9














          Your regex consumes the digit on the right. (d)s(d) matches and captures 1 in Some Words 1 2 3 4 into Group 1, then matches 1 whitespace, and then matches and consumes (i.e. adds to the match value and advances the regex index) 2. Then, the regex engine tries to find another match from the current index, that is already after 1 2. So, the regex does not match 2 3, but finds 3 4.



          Here is your regex demo and a diagram showing that:



          enter image description here



          Also, see the process of matching here:



          enter image description here



          Use lookarounds instead that are non-consuming:



          (?<=d)s+(?=d)


          See the regex demo



          enter image description here



          Details





          • (?<=d) - a positive lookbehind that matches a location in string immediately preceded with a digit


          • s+ - 1+ whitespaces


          • (?=d) - a positive lookahead that matches a location in string immediately followed with a digit.


          C# demo:



          string test = "Some Words 1 2 3 4";
          string result = Regex.Replace(test, @"(?<=d)s+(?=d)", "");


          See the online demo:



          var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
          foreach (var test in strs)
          {
          Console.WriteLine(Regex.Replace(test, @"(?<=d)s+(?=d)", ""));
          }


          Output:



          Some Words 1234
          Some Words That Should not be replaced 129123412
          test 98
          t e s t 98
          Another 12000





          share|improve this answer


























          • Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

            – nnty
            2 hours ago











          • @nnty Ok, just in case, I added diagrams.

            – Wiktor Stribiżew
            1 hour ago











          • @nnty I hope the animation showing how your regex works is fine.

            – Wiktor Stribiżew
            52 mins ago
















          9














          Your regex consumes the digit on the right. (d)s(d) matches and captures 1 in Some Words 1 2 3 4 into Group 1, then matches 1 whitespace, and then matches and consumes (i.e. adds to the match value and advances the regex index) 2. Then, the regex engine tries to find another match from the current index, that is already after 1 2. So, the regex does not match 2 3, but finds 3 4.



          Here is your regex demo and a diagram showing that:



          enter image description here



          Also, see the process of matching here:



          enter image description here



          Use lookarounds instead that are non-consuming:



          (?<=d)s+(?=d)


          See the regex demo



          enter image description here



          Details





          • (?<=d) - a positive lookbehind that matches a location in string immediately preceded with a digit


          • s+ - 1+ whitespaces


          • (?=d) - a positive lookahead that matches a location in string immediately followed with a digit.


          C# demo:



          string test = "Some Words 1 2 3 4";
          string result = Regex.Replace(test, @"(?<=d)s+(?=d)", "");


          See the online demo:



          var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
          foreach (var test in strs)
          {
          Console.WriteLine(Regex.Replace(test, @"(?<=d)s+(?=d)", ""));
          }


          Output:



          Some Words 1234
          Some Words That Should not be replaced 129123412
          test 98
          t e s t 98
          Another 12000





          share|improve this answer


























          • Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

            – nnty
            2 hours ago











          • @nnty Ok, just in case, I added diagrams.

            – Wiktor Stribiżew
            1 hour ago











          • @nnty I hope the animation showing how your regex works is fine.

            – Wiktor Stribiżew
            52 mins ago














          9












          9








          9







          Your regex consumes the digit on the right. (d)s(d) matches and captures 1 in Some Words 1 2 3 4 into Group 1, then matches 1 whitespace, and then matches and consumes (i.e. adds to the match value and advances the regex index) 2. Then, the regex engine tries to find another match from the current index, that is already after 1 2. So, the regex does not match 2 3, but finds 3 4.



          Here is your regex demo and a diagram showing that:



          enter image description here



          Also, see the process of matching here:



          enter image description here



          Use lookarounds instead that are non-consuming:



          (?<=d)s+(?=d)


          See the regex demo



          enter image description here



          Details





          • (?<=d) - a positive lookbehind that matches a location in string immediately preceded with a digit


          • s+ - 1+ whitespaces


          • (?=d) - a positive lookahead that matches a location in string immediately followed with a digit.


          C# demo:



          string test = "Some Words 1 2 3 4";
          string result = Regex.Replace(test, @"(?<=d)s+(?=d)", "");


          See the online demo:



          var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
          foreach (var test in strs)
          {
          Console.WriteLine(Regex.Replace(test, @"(?<=d)s+(?=d)", ""));
          }


          Output:



          Some Words 1234
          Some Words That Should not be replaced 129123412
          test 98
          t e s t 98
          Another 12000





          share|improve this answer















          Your regex consumes the digit on the right. (d)s(d) matches and captures 1 in Some Words 1 2 3 4 into Group 1, then matches 1 whitespace, and then matches and consumes (i.e. adds to the match value and advances the regex index) 2. Then, the regex engine tries to find another match from the current index, that is already after 1 2. So, the regex does not match 2 3, but finds 3 4.



          Here is your regex demo and a diagram showing that:



          enter image description here



          Also, see the process of matching here:



          enter image description here



          Use lookarounds instead that are non-consuming:



          (?<=d)s+(?=d)


          See the regex demo



          enter image description here



          Details





          • (?<=d) - a positive lookbehind that matches a location in string immediately preceded with a digit


          • s+ - 1+ whitespaces


          • (?=d) - a positive lookahead that matches a location in string immediately followed with a digit.


          C# demo:



          string test = "Some Words 1 2 3 4";
          string result = Regex.Replace(test, @"(?<=d)s+(?=d)", "");


          See the online demo:



          var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
          foreach (var test in strs)
          {
          Console.WriteLine(Regex.Replace(test, @"(?<=d)s+(?=d)", ""));
          }


          Output:



          Some Words 1234
          Some Words That Should not be replaced 129123412
          test 98
          t e s t 98
          Another 12000






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 52 mins ago

























          answered 2 hours ago









          Wiktor StribiżewWiktor Stribiżew

          319k16139221




          319k16139221













          • Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

            – nnty
            2 hours ago











          • @nnty Ok, just in case, I added diagrams.

            – Wiktor Stribiżew
            1 hour ago











          • @nnty I hope the animation showing how your regex works is fine.

            – Wiktor Stribiżew
            52 mins ago



















          • Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

            – nnty
            2 hours ago











          • @nnty Ok, just in case, I added diagrams.

            – Wiktor Stribiżew
            1 hour ago











          • @nnty I hope the animation showing how your regex works is fine.

            – Wiktor Stribiżew
            52 mins ago

















          Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

          – nnty
          2 hours ago





          Thank you ! Good answer, but @heinzi 's explanation was a little bit more clearer. Therefore I accepted his answer.

          – nnty
          2 hours ago













          @nnty Ok, just in case, I added diagrams.

          – Wiktor Stribiżew
          1 hour ago





          @nnty Ok, just in case, I added diagrams.

          – Wiktor Stribiżew
          1 hour ago













          @nnty I hope the animation showing how your regex works is fine.

          – Wiktor Stribiżew
          52 mins ago





          @nnty I hope the animation showing how your regex works is fine.

          – Wiktor Stribiżew
          52 mins ago


















          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%2f54883163%2fregex-replace-seems-to-replace-only-first-occurrence%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

          Paper upload error, “Upload failed: The top margin is 0.715 in on page 3, which is below the required...

          Emraan Hashmi Filmografia | Linki zewnętrzne | Menu nawigacyjneGulshan GroverGulshan...

          How can I write this formula?newline and italics added with leqWhy does widehat behave differently if I...