简体   繁体   English

需要帮助在Java中拆分字符串

[英]Need help to split string in java

Please help me to split string like this "mumbai (or) pune" using java. 请帮助我使用Java分割类似“孟买(或)浦那”的字符串。

I want the string after ")", I tried using string.split() but not working on above String format. 我想要“)”之后的字符串,我尝试使用string.split()但无法在上述String格式上使用。

my expected output is "pune". 我的预期输出是“ 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(); 使用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 最佳方法:阅读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);        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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