[英]How to extract the desired strings from a bracketed string
Sorry for the bad title. 对不起,标题不好。 Feel free to make a better title. 随意做出更好的标题。
I have a string like follows 我有一个如下的字符串
[Munich, Germany],[Jingle Pot Rd, Nanaimo, BC, Canada],...
Now i want to convert this list into a LinkedList locations where 现在我想将此列表转换为LinkedList位置,其中
so 0 index -> Munich, Germany
1 index -> Jingle Pot Rd, Nanaimo, BC, Canada
and so on.. 等等..
How can i do this very efficiently in java. 我如何在Java中非常有效地做到这一点。 I thought of using string.split() but will that would be the efficient way to do something like this. 我曾考虑过使用string.split(),但这将是执行此类操作的有效方法。
Try matching with a capturing group on "anything between brackets" (eg \\[(.*?)\\]
) and adding the group to a list: 尝试与“方括号之间的任何内容”上的捕获组匹配(例如\\[(.*?)\\]
),然后将该组添加到列表中:
public static List<String> getStringsInBrackets(String s) {
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(s);
List<String> list = new ArrayList<String>();
while (m.find()) { list.add(m.group(1)); }
return list;
}
For example: 例如:
public static void main(String args[]) {
String s = "[Munich, Germany],[Jingle Pot Rd, Nanaimo, BC, Canada]";
List<String> ss = getStringsInBrackets(s);
ss.get(0); // => "Munich, Germany"
ss.get(1); // => "Jingle Pot Rd, Nanaimo, BC, Canada"
}
If performance becomes a concern you can pre-compile the pattern. 如果性能成为问题,则可以预编译模式。
What about using a Regex? 使用正则表达式怎么办? http://ideone.com/lZK0wo http://ideone.com/lZK0wo
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher("[Munich, Germany],[Jingle Pot Rd, Nanaimo, BC, Canada]");
while(m.find()) {
System.out.println(m.group(1));
}
}
}
Prints: 印刷品:
Line 1: Munich, Germany
Line 2: Jingle Pot Rd, Nanaimo, BC, Canada
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.