我有:
String s=" \"son of god\"\"cried out\" a good day and ok ";
这在屏幕上显示为:
"son of god""cried out" a good day and ok
Pattern phrasePattern=Pattern.compile("(\".*?\")");
Matcher m=phrasePattern.matcher(s);
我希望获取所有被“”包围的短语并将其添加到ArrayList<String>
。它可能有两个以上这样的短语。如何获取每个短语并放入Arraylist
?
答案 0 :(得分:1)
使用Matcher
,您可以在90%的路上行驶。您只需要#find
方法。
ArrayList<String> list = new ArrayList<>();
while(m.find()) {
list.add(m.group());
}
答案 1 :(得分:1)
另一种方法,我只建议它,因为你没有明确说你必须使用正则表达式匹配,就是在"
上拆分。每一件都是你的兴趣。
public static void main(String[] args) {
String[] testCases = new String[] {
" \"son of god\"\"cried out\" a good day and ok ",
"\"starts with a quote\" and then \"forgot the end quote",
};
for (String testCase : testCases) {
System.out.println("Input: " + testCase);
String[] pieces = testCase.split("\"");
System.out.println("Split into : " + pieces.length + " pieces");
for (int i = 0; i < pieces.length; i++) {
if (i%2 == 1) {
System.out.println(pieces[i]);
}
}
System.out.println();
}
}
结果:
Input: "son of god""cried out" a good day and ok
Split into : 5 pieces
son of god
cried out
Input: "starts with a quote" and then "forgot the end quote
Split into : 4 pieces
starts with a quote
forgot the end quote
如果您想确保偶数个双引号,请确保拆分结果有奇数。