By innovativesahil

2018-08-10 10:20:42 8 Comments

So here is the problem:
A string is composed of only a, b, c, d.

The string is said to be balanced if:

  1. sum of occurence of a and c is even
  2. sum of occurence of b and d is even

I have to write a regular expression to check if the string is balanced string in java.
Please help me out.


@zhh 2018-08-10 11:16:03

For the first condition. The sum of a and c is even, which means you can match the pairs of ac, aa, ca and cc.

Using regex it is written as


Since there are other characters in those a and c, so it becomes


And same for the second condition


Because the input string should contain only a,b,c,d, so [^ac] should be [bd], [^bd] should be [ac].

String cond1 = "(([bd]*[ac]){2})*[bd]*";
String cond2 = "(([ac]*[bd]){2})*[ac]*";
String input = "abcdabcd";
boolean matches = Pattern.matches(cond1, input) && Pattern.matches(cond2, input);

This question shows us how those two conditions can be combined into one regex using lookaheads:

String regex = "(?=^(([ac]*[bd]){2})*[ac]*$)(([bd]*[ac]){2})*[bd]*";

@Malte Hartwig 2018-08-10 11:34:25

You can combine both regex parts into one by turning them into lookaheads on a anything-match: (?=^(([ac]*[bd]){2})*[ac]*$)(?=^(([bd]*[ac]){2})*[bd]*$).*. Note that I had to add ^ and $. See this question for details.

@zhh 2018-08-10 11:52:24

@Malte Hartwig Thanks, I have updated my answer.

@innovativesahil 2018-08-10 16:42:07

Thanks everyone you all have been greatly helpful.

@bitsobits 2018-08-10 10:31:36

The code will be way easier and readable if you dont use regex and instead use java libraries.
Use StringUtils library with countMatches() or countOccurencesOf() method.
Add the dependency:


Java Code:

String customString;   
int aCount = StringUtils.countMatches(customString, "a");
int bCount = StringUtils.countMatches(customString, "b");
int abSum = aCount + bCount;

// Check sum is even or odd.
if ( (abSum & 1) == 0 ) { even... } else { odd... }

Related Questions

Sponsored Content

59 Answered Questions

[SOLVED] What is the difference between String and string in C#?

3 Answered Questions

28 Answered Questions

50 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

44 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

71 Answered Questions

19 Answered Questions

[SOLVED] Why is char[] preferred over String for passwords?

17 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

6 Answered Questions

[SOLVED] \d is less efficient than [0-9]

Sponsored Content