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
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
add a comment |
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
add a comment |
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
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
java regex
edited Sep 13 '10 at 0:53
NETQuestion
asked Sep 12 '10 at 23:42
NETQuestionNETQuestion
57951324
57951324
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
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.
+1 for generic sol.
– Emil
Sep 13 '10 at 7:04
add a comment |
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.
add a comment |
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.
add a comment |
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;
Poly's answer is better and a generic one.I'm just giving an alternative method.
– Emil
Sep 13 '10 at 7:01
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
+1 for generic sol.
– Emil
Sep 13 '10 at 7:04
add a comment |
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.
+1 for generic sol.
– Emil
Sep 13 '10 at 7:04
add a comment |
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.
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.
answered Sep 13 '10 at 0:33
polygenelubricantspolygenelubricants
286k101511592
286k101511592
+1 for generic sol.
– Emil
Sep 13 '10 at 7:04
add a comment |
+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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Sep 12 '10 at 23:48
Mark ByersMark Byers
595k12713631345
595k12713631345
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Sep 12 '10 at 23:57
Jeanne BoyarskyJeanne Boyarsky
11k14054
11k14054
add a comment |
add a comment |
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;
Poly's answer is better and a generic one.I'm just giving an alternative method.
– Emil
Sep 13 '10 at 7:01
add a comment |
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;
Poly's answer is better and a generic one.I'm just giving an alternative method.
– Emil
Sep 13 '10 at 7:01
add a comment |
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;
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;
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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