pairRemoval(String, String, String)
This is a public static function that takes three Strings as arguments and returns a String.
You will be given three strings, the first string is a sentence known as text that contains at least one occurrence of left pattern and right pattern. The second and third arguments of the function are the left and right patterns respectively. Left pattern and right pattern are single characters strings that you are attempting to remove from the string. Your goal is to remove only the patterns when the left pattern has an equal number of corresponding right patterns. The patterns are removed in pairs only when there is a balanced number of left and right patterns. The patterns may be nested within the text and there is no guarantee that a left pattern will occur before the right pattern.
Arguments: String text - The string with the substring to be removed
String leftPattern - A pattern that the substring must start with
String rightPattern - A pattern that the substring must end with
returns String - The given text with the paired patterns removed
Example: Example 1:
text = { { Muscat } } { } mecum tollgate } poultry quarrymen pantheon asteria
leftPattern = {
rightPattern = }
return = Muscat mecum tollgate } poultry quarrymen pantheon asteria
Example 2:
text = merioneth ( smickly helotage yarr ) ethmoidal ) ) ) digitinervate
leftPattern = (
rightPattern = )
return =. merioneth smickly helotage yarr ethmoidal ) ) ) digitinervate
Example 3:
text = southland palladic } { pasillo { } seeableness } { { normanesque
leftPattern = {
rightPattern = }
return = southland palladic pasillo seeableness { normanesque
This is what I tried
public static String pairRemoval(String text, String leftPattern, String rightPattern) {
String finalText = ""
int indexOf1LeftP = text.indexOf(leftPattern)
int indexOfLastLeftP = text.lastIndexOf(leftPattern)
int indexOf1RightP = text.indexOf(rightPattern)
int indexOfLastRightP = text.lastIndexOf(rightPattern)
for (int i = indexOf1LeftP; i <= indexOfLastLeftP; i++) {
for (int j = indexOf1RightP; j <= indexOfLastRightP; j++){
String leftChar = text.substring(i, i + 1)
String rightChar = text.substring(j, j + 1)
if (leftChar.equals(leftPattern) && rightChar.equals(rightPattern)) {
finalText = text.replaceFirst(rightChar, "").replaceFirst(leftChar, "")
}
}
}
return finalText;
}
And I got this error:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1