I wanna a regular expression that exp-b occurs the SAME times as exp-a. Just like "(" and ")". For example, "x" vs "y", "abxefyg" matches, "abxefyyg" not, and "abxxefyyg" does.
How should I code it in Java?
Any advice will be appreciated.
Thanks.
I wanna a regular expression that exp-b occurs the SAME times as exp-a. Just like "(" and ")". For example, "x" vs "y", "abxefyg" matches, "abxefyyg" not, and "abxxefyyg" does.
How should I code it in Java?
Any advice will be appreciated.
Thanks.
I believe this is what you want.
\\1
is a backreference to reference what the capture group matched.So this replaces all double characters with an empty string.
String str = "AAabbBCCeeFF--#";
str = str.replaceAll("(.)\\1", "");
System.out.println(str);
This prints
aB#
Just like "(" and ")"
Parentheses must be balanced, i.e. for every (
there must be a following )
, and you cannot have a )
without a matching preceding (
.
Regex cannot do this. Just write a simple loop, and keep track of the nesting depth, e.g.
public static boolean isBalanced(String text, char startChar, char endChar) {
int depth = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == startChar)
depth++;
else if (c == endChar && --depth < 0)
return false; // endChar without matching startChar
}
return (depth == 0); // check startChar without matching endChar
}
Test 1
System.out.println(isBalanced("abxefyg", 'x', 'y'));
System.out.println(isBalanced("abxefyyg", 'x', 'y'));
System.out.println(isBalanced("abxxefyyg", 'x', 'y'));
Test 2
System.out.println(isBalanced("ab(ef)g", '(', ')'));
System.out.println(isBalanced("ab(ef))g", '(', ')'));
System.out.println(isBalanced("ab((ef))g", '(', ')'));
Output from both
true
false
true
This answer assumes that you want to assert whether a string has the same length of sequence of two different characters. Using your sample input, we can first do a regex replacement to remove any characters other than x
and y
. Then, split on (?<=(.))(?!\1)
to generate a string array with two entries, one for the x
sequence, and one for the y
sequence. Finally, assert that these two strings are the same length.
String input = "abxxefyyg";
input = input.replaceAll("[^xy]+", "");
String[] parts = input.split("(?<=(.))(?!\\1)");
System.out.println(Arrays.toString(parts));
if (parts[0].length() == parts[1].length()) {
System.out.println("MATCH");
}
else {
System.out.println("NO MATCH");
}
This prints:
[xx, yy]
MATCH
Here is an explanation of how the regex works:
(?<=(.)) look behind and capture a single character
(?!\1) look ahead and assert that what follows is NOT the same character
So, if we split on (?<=(.))(?!\1)
, then we would be splitting in between any two characters which are not the same. After doing the regex replacement on the input abxxefyyg
, we would be left with xxyy
. Splitting using the above pattern generates an array with two terms, xx
and yy
.