Replace comma in parentheses using regex in java2019 Community Moderator ElectionI want to replace ',' on the 150th location in a String with a <br>Is Java “pass-by-reference” or “pass-by-value”?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How to replace all occurrences of a string in JavaScriptRegEx match open tags except XHTML self-contained tagsHow do I convert a String to an int in Java?Creating a memory leak with JavaWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regex

Book about superhumans hiding among normal humans

What is the significance behind "40 days" that often appears in the Bible?

Why one should not leave fingerprints on bulbs and plugs?

Have the tides ever turned twice on any open problem?

How to write cleanly even if my character uses expletive language?

Why no Iridium-level flares from other satellites?

My adviser wants to be the first author

How to deal with taxi scam when on vacation?

Shortcut for setting origin to vertex

Bacteria contamination inside a thermos bottle

Professor being mistaken for a grad student

What options are left, if Britain cannot decide?

New passport but visa is in old (lost) passport

Did Ender ever learn that he killed Stilson and/or Bonzo?

PTIJ: Who should I vote for? (21st Knesset Edition)

Is there a symmetric-key algorithm which we can use for creating a signature?

Python if-else code style for reduced code for rounding floats

Problem with FindRoot

Violin - Can double stops be played when the strings are not next to each other?

Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?

Employee lack of ownership

Official degrees of earth’s rotation per day

How could an airship be repaired midflight?

Why did it take so long to abandon sail after steamships were demonstrated?



Replace comma in parentheses using regex in java



2019 Community Moderator ElectionI want to replace ',' on the 150th location in a String with a <br>Is Java “pass-by-reference” or “pass-by-value”?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How to replace all occurrences of a string in JavaScriptRegEx match open tags except XHTML self-contained tagsHow do I convert a String to an int in Java?Creating a memory leak with JavaWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regex










8















I want to replace comma when its inside parentheses only.



For Example



 Progamming languages (Java, C#, Perl)


TO



Progamming languages (Java or C# or Perl)


but it should not repace comma in following string



Progamming languages Java, C#, Perl


CODE



It will replace correctly but its not matching up.



 String test = "Progamming languages (Java, C#, Perl)";
String test1 = "Progamming languages Java, C#, Perl"


String foo = replaceComma(test);
String foo1 = replaceComma(test1);


private static String replaceComma(String test)

String patternStr= "\((?:.*)(,)(?:.*)\)";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher= pattern.matcher(test);

if(matcher.matches())

return test.replaceAll("(,)", " or ");


return test;




UPDATE



String.replaceAll("(,)", " or "); will not work when you have string like this



String test = "Learning, languages (Java, C#, Perl)";



so you have to use @polygenelubricants code










share|improve this question




























    8















    I want to replace comma when its inside parentheses only.



    For Example



     Progamming languages (Java, C#, Perl)


    TO



    Progamming languages (Java or C# or Perl)


    but it should not repace comma in following string



    Progamming languages Java, C#, Perl


    CODE



    It will replace correctly but its not matching up.



     String test = "Progamming languages (Java, C#, Perl)";
    String test1 = "Progamming languages Java, C#, Perl"


    String foo = replaceComma(test);
    String foo1 = replaceComma(test1);


    private static String replaceComma(String test)

    String patternStr= "\((?:.*)(,)(?:.*)\)";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher= pattern.matcher(test);

    if(matcher.matches())

    return test.replaceAll("(,)", " or ");


    return test;




    UPDATE



    String.replaceAll("(,)", " or "); will not work when you have string like this



    String test = "Learning, languages (Java, C#, Perl)";



    so you have to use @polygenelubricants code










    share|improve this question


























      8












      8








      8


      1






      I want to replace comma when its inside parentheses only.



      For Example



       Progamming languages (Java, C#, Perl)


      TO



      Progamming languages (Java or C# or Perl)


      but it should not repace comma in following string



      Progamming languages Java, C#, Perl


      CODE



      It will replace correctly but its not matching up.



       String test = "Progamming languages (Java, C#, Perl)";
      String test1 = "Progamming languages Java, C#, Perl"


      String foo = replaceComma(test);
      String foo1 = replaceComma(test1);


      private static String replaceComma(String test)

      String patternStr= "\((?:.*)(,)(?:.*)\)";
      Pattern pattern = Pattern.compile(patternStr);
      Matcher matcher= pattern.matcher(test);

      if(matcher.matches())

      return test.replaceAll("(,)", " or ");


      return test;




      UPDATE



      String.replaceAll("(,)", " or "); will not work when you have string like this



      String test = "Learning, languages (Java, C#, Perl)";



      so you have to use @polygenelubricants code










      share|improve this question
















      I want to replace comma when its inside parentheses only.



      For Example



       Progamming languages (Java, C#, Perl)


      TO



      Progamming languages (Java or C# or Perl)


      but it should not repace comma in following string



      Progamming languages Java, C#, Perl


      CODE



      It will replace correctly but its not matching up.



       String test = "Progamming languages (Java, C#, Perl)";
      String test1 = "Progamming languages Java, C#, Perl"


      String foo = replaceComma(test);
      String foo1 = replaceComma(test1);


      private static String replaceComma(String test)

      String patternStr= "\((?:.*)(,)(?:.*)\)";
      Pattern pattern = Pattern.compile(patternStr);
      Matcher matcher= pattern.matcher(test);

      if(matcher.matches())

      return test.replaceAll("(,)", " or ");


      return test;




      UPDATE



      String.replaceAll("(,)", " or "); will not work when you have string like this



      String test = "Learning, languages (Java, C#, Perl)";



      so you have to use @polygenelubricants code







      java regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 13 '10 at 0:53







      NETQuestion

















      asked Sep 12 '10 at 23:42









      NETQuestionNETQuestion

      57951324




      57951324






















          4 Answers
          4






          active

          oldest

          votes


















          7














          You can use positive lookahead (?=…) like this:



           String COMMA_INSIDE = ",(?=[^()]*\))";
          String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
          System.out.println(
          text.replaceAll(COMMA_INSIDE, " OR")
          );
          // a, b, c, (d OR e OR f), g, h, (i OR j OR k)


          This matches a comma, but only if the first parenthesis to its right is of the closing kind.



          The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The ) (written as "\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.



          This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.






          share|improve this answer























          • +1 for generic sol.

            – Emil
            Sep 13 '10 at 7:04


















          1














          Your error is using matches instead of find here:



          if (matcher.find())


          From the documentation:




          • The matches method attempts to match the entire input sequence against the pattern.

          • The find method scans the input sequence looking for the next subsequence that matches the pattern.



          But your code also simplifies the issue somewhat - it replaces all commas even if only one of them is in parentheses. It's probably not a good idea to use regular expressions for this sort of task.



          Instead you could scan the string one character at a time and count how many pairs of parentheses you are inside. When you see a ( increase the count, and when you see a ) decrease the count. If you see a , then check if the current count is zero.






          share|improve this answer






























            0














            Another approach is to use positive lookahead and positive lookbehind in your regular expression. That way you can search for commas that occur after a '(', but before a ')'.



            (?=X) positive lookahead



            (?<=X) positive lookbehind



            Mark is correct you need a loop instead of replaceAll. But you can still use a regular expression using the technique I've described.






            share|improve this answer






























              0














              String replaceComma(String input)

              String[] strSplit=input.split("[\(\)]");
              if(strSplit.length==2)
              input=input.replaceAll(", "," or ");
              return input;



              UPDATE: For String's like "Learning, languages (Java, C#, Perl)"



              String replaceComma(String input)

              String[] splitStr=input.split("[\(\)]");
              if(splitStr.length==2)
              input=input.replace(splitStr[1],splitStr[1].replaceAll(", ", " or "));
              return input;






              share|improve this answer

























              • Poly's answer is better and a generic one.I'm just giving an alternative method.

                – Emil
                Sep 13 '10 at 7:01










              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%2f3697139%2freplace-comma-in-parentheses-using-regex-in-java%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              7














              You can use positive lookahead (?=…) like this:



               String COMMA_INSIDE = ",(?=[^()]*\))";
              String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
              System.out.println(
              text.replaceAll(COMMA_INSIDE, " OR")
              );
              // a, b, c, (d OR e OR f), g, h, (i OR j OR k)


              This matches a comma, but only if the first parenthesis to its right is of the closing kind.



              The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The ) (written as "\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.



              This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.






              share|improve this answer























              • +1 for generic sol.

                – Emil
                Sep 13 '10 at 7:04















              7














              You can use positive lookahead (?=…) like this:



               String COMMA_INSIDE = ",(?=[^()]*\))";
              String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
              System.out.println(
              text.replaceAll(COMMA_INSIDE, " OR")
              );
              // a, b, c, (d OR e OR f), g, h, (i OR j OR k)


              This matches a comma, but only if the first parenthesis to its right is of the closing kind.



              The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The ) (written as "\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.



              This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.






              share|improve this answer























              • +1 for generic sol.

                – Emil
                Sep 13 '10 at 7:04













              7












              7








              7







              You can use positive lookahead (?=…) like this:



               String COMMA_INSIDE = ",(?=[^()]*\))";
              String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
              System.out.println(
              text.replaceAll(COMMA_INSIDE, " OR")
              );
              // a, b, c, (d OR e OR f), g, h, (i OR j OR k)


              This matches a comma, but only if the first parenthesis to its right is of the closing kind.



              The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The ) (written as "\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.



              This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.






              share|improve this answer













              You can use positive lookahead (?=…) like this:



               String COMMA_INSIDE = ",(?=[^()]*\))";
              String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
              System.out.println(
              text.replaceAll(COMMA_INSIDE, " OR")
              );
              // a, b, c, (d OR e OR f), g, h, (i OR j OR k)


              This matches a comma, but only if the first parenthesis to its right is of the closing kind.



              The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The ) (written as "\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.



              This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 13 '10 at 0:33









              polygenelubricantspolygenelubricants

              286k101511592




              286k101511592












              • +1 for generic sol.

                – Emil
                Sep 13 '10 at 7:04

















              • +1 for generic sol.

                – Emil
                Sep 13 '10 at 7:04
















              +1 for generic sol.

              – Emil
              Sep 13 '10 at 7:04





              +1 for generic sol.

              – Emil
              Sep 13 '10 at 7:04













              1














              Your error is using matches instead of find here:



              if (matcher.find())


              From the documentation:




              • The matches method attempts to match the entire input sequence against the pattern.

              • The find method scans the input sequence looking for the next subsequence that matches the pattern.



              But your code also simplifies the issue somewhat - it replaces all commas even if only one of them is in parentheses. It's probably not a good idea to use regular expressions for this sort of task.



              Instead you could scan the string one character at a time and count how many pairs of parentheses you are inside. When you see a ( increase the count, and when you see a ) decrease the count. If you see a , then check if the current count is zero.






              share|improve this answer



























                1














                Your error is using matches instead of find here:



                if (matcher.find())


                From the documentation:




                • The matches method attempts to match the entire input sequence against the pattern.

                • The find method scans the input sequence looking for the next subsequence that matches the pattern.



                But your code also simplifies the issue somewhat - it replaces all commas even if only one of them is in parentheses. It's probably not a good idea to use regular expressions for this sort of task.



                Instead you could scan the string one character at a time and count how many pairs of parentheses you are inside. When you see a ( increase the count, and when you see a ) decrease the count. If you see a , then check if the current count is zero.






                share|improve this answer

























                  1












                  1








                  1







                  Your error is using matches instead of find here:



                  if (matcher.find())


                  From the documentation:




                  • The matches method attempts to match the entire input sequence against the pattern.

                  • The find method scans the input sequence looking for the next subsequence that matches the pattern.



                  But your code also simplifies the issue somewhat - it replaces all commas even if only one of them is in parentheses. It's probably not a good idea to use regular expressions for this sort of task.



                  Instead you could scan the string one character at a time and count how many pairs of parentheses you are inside. When you see a ( increase the count, and when you see a ) decrease the count. If you see a , then check if the current count is zero.






                  share|improve this answer













                  Your error is using matches instead of find here:



                  if (matcher.find())


                  From the documentation:




                  • The matches method attempts to match the entire input sequence against the pattern.

                  • The find method scans the input sequence looking for the next subsequence that matches the pattern.



                  But your code also simplifies the issue somewhat - it replaces all commas even if only one of them is in parentheses. It's probably not a good idea to use regular expressions for this sort of task.



                  Instead you could scan the string one character at a time and count how many pairs of parentheses you are inside. When you see a ( increase the count, and when you see a ) decrease the count. If you see a , then check if the current count is zero.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 12 '10 at 23:48









                  Mark ByersMark Byers

                  595k12713631345




                  595k12713631345





















                      0














                      Another approach is to use positive lookahead and positive lookbehind in your regular expression. That way you can search for commas that occur after a '(', but before a ')'.



                      (?=X) positive lookahead



                      (?<=X) positive lookbehind



                      Mark is correct you need a loop instead of replaceAll. But you can still use a regular expression using the technique I've described.






                      share|improve this answer



























                        0














                        Another approach is to use positive lookahead and positive lookbehind in your regular expression. That way you can search for commas that occur after a '(', but before a ')'.



                        (?=X) positive lookahead



                        (?<=X) positive lookbehind



                        Mark is correct you need a loop instead of replaceAll. But you can still use a regular expression using the technique I've described.






                        share|improve this answer

























                          0












                          0








                          0







                          Another approach is to use positive lookahead and positive lookbehind in your regular expression. That way you can search for commas that occur after a '(', but before a ')'.



                          (?=X) positive lookahead



                          (?<=X) positive lookbehind



                          Mark is correct you need a loop instead of replaceAll. But you can still use a regular expression using the technique I've described.






                          share|improve this answer













                          Another approach is to use positive lookahead and positive lookbehind in your regular expression. That way you can search for commas that occur after a '(', but before a ')'.



                          (?=X) positive lookahead



                          (?<=X) positive lookbehind



                          Mark is correct you need a loop instead of replaceAll. But you can still use a regular expression using the technique I've described.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 12 '10 at 23:57









                          Jeanne BoyarskyJeanne Boyarsky

                          11k14054




                          11k14054





















                              0














                              String replaceComma(String input)

                              String[] strSplit=input.split("[\(\)]");
                              if(strSplit.length==2)
                              input=input.replaceAll(", "," or ");
                              return input;



                              UPDATE: For String's like "Learning, languages (Java, C#, Perl)"



                              String replaceComma(String input)

                              String[] splitStr=input.split("[\(\)]");
                              if(splitStr.length==2)
                              input=input.replace(splitStr[1],splitStr[1].replaceAll(", ", " or "));
                              return input;






                              share|improve this answer

























                              • Poly's answer is better and a generic one.I'm just giving an alternative method.

                                – Emil
                                Sep 13 '10 at 7:01















                              0














                              String replaceComma(String input)

                              String[] strSplit=input.split("[\(\)]");
                              if(strSplit.length==2)
                              input=input.replaceAll(", "," or ");
                              return input;



                              UPDATE: For String's like "Learning, languages (Java, C#, Perl)"



                              String replaceComma(String input)

                              String[] splitStr=input.split("[\(\)]");
                              if(splitStr.length==2)
                              input=input.replace(splitStr[1],splitStr[1].replaceAll(", ", " or "));
                              return input;






                              share|improve this answer

























                              • Poly's answer is better and a generic one.I'm just giving an alternative method.

                                – Emil
                                Sep 13 '10 at 7:01













                              0












                              0








                              0







                              String replaceComma(String input)

                              String[] strSplit=input.split("[\(\)]");
                              if(strSplit.length==2)
                              input=input.replaceAll(", "," or ");
                              return input;



                              UPDATE: For String's like "Learning, languages (Java, C#, Perl)"



                              String replaceComma(String input)

                              String[] splitStr=input.split("[\(\)]");
                              if(splitStr.length==2)
                              input=input.replace(splitStr[1],splitStr[1].replaceAll(", ", " or "));
                              return input;






                              share|improve this answer















                              String replaceComma(String input)

                              String[] strSplit=input.split("[\(\)]");
                              if(strSplit.length==2)
                              input=input.replaceAll(", "," or ");
                              return input;



                              UPDATE: For String's like "Learning, languages (Java, C#, Perl)"



                              String replaceComma(String input)

                              String[] splitStr=input.split("[\(\)]");
                              if(splitStr.length==2)
                              input=input.replace(splitStr[1],splitStr[1].replaceAll(", ", " or "));
                              return input;







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Sep 13 '10 at 6:57

























                              answered Sep 13 '10 at 6:29









                              EmilEmil

                              8,396175599




                              8,396175599












                              • Poly's answer is better and a generic one.I'm just giving an alternative method.

                                – Emil
                                Sep 13 '10 at 7:01

















                              • Poly's answer is better and a generic one.I'm just giving an alternative method.

                                – Emil
                                Sep 13 '10 at 7:01
















                              Poly's answer is better and a generic one.I'm just giving an alternative method.

                              – Emil
                              Sep 13 '10 at 7:01





                              Poly's answer is better and a generic one.I'm just giving an alternative method.

                              – Emil
                              Sep 13 '10 at 7:01

















                              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%2f3697139%2freplace-comma-in-parentheses-using-regex-in-java%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

                              1928 у кіно

                              Захаров Федір Захарович

                              Ель Греко