【问题标题】:java regular expression for String surrounded by ""用“”包围的字符串的java正则表达式
【发布时间】:2016-04-19 02:12:30
【问题描述】:

我有:

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>。它可能有超过 2 个这样的短语。如何获取每个短语并放入我的Arraylist

【问题讨论】:

  • 你将如何处理字符串Then John said "I talked to Fred and he said 'I don't like it'"
  • @JimGarrison 如果您在那对单引号中有一对双引号,那将是一个更好的问题。

标签: java regex pattern-matching


【解决方案1】:

使用您的Matcher,您已经完成了 90% 的工作。你只需要#find 方法。

ArrayList<String> list = new ArrayList<>();
while(m.find()) {
    list.add(m.group());
}

【讨论】:

    【解决方案2】:

    另一种方法是在" 上拆分,因为您没有明确说必须使用正则表达式匹配,所以我只建议这样做。其他每一件作品都是您的兴趣所在。

    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
    

    如果要确保双引号的个数为偶数,请确保拆分结果为奇数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多