I am giving input as a String s1= (RT)PO(Q(IT)); and want output as RTPO(QIT) as a String. If there is a parenthesis as a first character I want to remove that parentheses and its closing parentheses. Also, if there are 2 continuous parenthesis then remove the inside one. If I get indexes of these parentheses then I can remove them.
Can somebody help me with that? I am not good with Regex.
Regex is no use for this. You can use the indexOf(char ch, int fromIndex):
; and StringBuilder
also have a deleteCharAt(int position)
. So you just have to save the indexes of all opening and closing parenthesis in an ArrayList
and delete them after. The subtility is of course, when you get a (
, then get the )
after, and look for the next (
only after the last )
(using the fromIndex
parameter) and using some counter to remember how much parenthesis deep you are.
If there is a parenthesis as a first character I want to remove that parentheses and its closing parentheses.
***You can improvise the code for the rest
package mypackage;
import java.util.ArrayList; import java.util.Scanner;
public class BracketsModifier {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter the sample string ");
String sampleString=scn.next();
int leftBracketCounter=0;
int rightBrackerCounter=0;
for(int i=0;i<sampleString.length();i++)
{
if(sampleString.charAt(i)=='(')
{
leftBracketCounter++;
}
else
if(sampleString.charAt(i)==')')
{
rightBrackerCounter++;
// System.out.println("first braket encounterd @ loc "+i);
}
}
if(leftBracketCounter==rightBrackerCounter)
{
System.out.println("balanced String entered");
}
else {
System.out.println("not a valid input");
}
ArrayList< String>alist=new ArrayList<>();
int last_bracket_loc=0;
for(int i=0;i<sampleString.length();i++)
{
if(sampleString.charAt(i)=='(')
{
alist.add("(");
}
else if (sampleString.charAt(i)==')') {
int alist_size=alist.size();
alist.remove(alist_size-1);
last_bracket_loc=i;
}
}
String temp = sampleString.substring(1,last_bracket_loc);
System.out.println("finally the data remained is "+ temp);
}
}
var demo = "(RT)PO(Q(IT))"; var regex = /\\((\\w+)\\)/g; document.write(demo.replace(regex,"$1"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.