Regex for splitting a string using space when not surrounded by single or double quotes

后端 未结 15 2442
梦毁少年i
梦毁少年i 2020-11-22 03:15

I\'m new to regular expressions and would appreciate your help. I\'m trying to put together an expression that will split the example string using all spaces that are not s

15条回答
  •  借酒劲吻你
    2020-11-22 03:43

    String.split() is not helpful here because there is no way to distinguish between spaces within quotes (don't split) and those outside (split). Matcher.lookingAt() is probably what you need:

    String str = "This is a string that \"will be\" highlighted when your 'regular expression' matches something.";
    str = str + " "; // add trailing space
    int len = str.length();
    Matcher m = Pattern.compile("((\"[^\"]+?\")|('[^']+?')|([^\\s]+?))\\s++").matcher(str);
    
    for (int i = 0; i < len; i++)
    {
        m.region(i, len);
    
        if (m.lookingAt())
        {
            String s = m.group(1);
    
            if ((s.startsWith("\"") && s.endsWith("\"")) ||
                (s.startsWith("'") && s.endsWith("'")))
            {
                s = s.substring(1, s.length() - 1);
            }
    
            System.out.println(i + ": \"" + s + "\"");
            i += (m.group(0).length() - 1);
        }
    }
    

    which produces the following output:

    0: "This"
    5: "is"
    8: "a"
    10: "string"
    17: "that"
    22: "will be"
    32: "highlighted"
    44: "when"
    49: "your"
    54: "regular expression"
    75: "matches"
    83: "something."
    

提交回复
热议问题