简体   繁体   中英

Need help to split string in java

Please help me to split string like this "mumbai (or) pune" using java.

I want the string after ")", I tried using string.split() but not working on above String format.

my expected output is "pune".

input:

String abc="mumbai (or) pune"

output:

String result="pune".

如果您输入的字符串始终与您显示的字符串相似:

yourString.split("\\)")[1].trim();

It doesn't work because ) is special in regex. Escape the regex with \\\\ .

Use string.split("\\\\)")[1].trim(); instead.

You can split it into parts:

String abc="mumbai (or) pune"
String result = "pune";

String[] parts = abc.split(" ");
String partOne = parts[0];
String partTwo = parts[2];

if (partOne == result){
   System.out.println(partOne);
}
else{
   System.out.println(partTwo);
}

Try this:

String s = "mumbai (or) pune";
String result = s.substring(s.lastIndexOf(')') + 1).trim();

A replace would be actually more efficient here.

Use :

 String abc="mumbai (or) pune";
 abc = abc.replaceAll(".*\\s+(\\w+)","$1");
 // abc will be "pune" here  

There are many ways to do the simple thing which you are looking for. Best approach: Read of String Operations in Java

Following are just some ways to achieve what you need:

 public static void main(String[] args)
{
    String output1 = "mumbai (or) pune";
    String output2 = output1.split("or\\) ")[1];
    String output3 = output1.substring(output1.indexOf(")")+2);;        

    System.out.println(output1);
    System.out.println(output2);
    System.out.println(output3);        
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM