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

后端 未结 15 2149
梦毁少年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:24

    If you want to allow escaped quotes inside the string, you can use something like this:

    (?:(['"])(.*?)(?<!\\)(?>\\\\)*\1|([^\s]+))
    

    Quoted strings will be group 2, single unquoted words will be group 3.

    You can try it on various strings here: http://www.fileformat.info/tool/regex.htm or http://gskinner.com/RegExr/

    0 讨论(0)
  • 2020-11-22 03:26

    I liked Marcus's approach, however, I modified it so that I could allow text near the quotes, and support both " and ' quote characters. For example, I needed a="some value" to not split it into [a=, "some value"].

    (?<!\\G\\S{0,99999}[\"'].{0,99999})\\s|(?<=\\G\\S{0,99999}\".{0,99999}\"\\S{0,99999})\\s|(?<=\\G\\S{0,99999}'.{0,99999}'\\S{0,99999})\\s"
    
    0 讨论(0)
  • 2020-11-22 03:32

    I don't understand why all the others are proposing such complex regular expressions or such long code. Essentially, you want to grab two kinds of things from your string: sequences of characters that aren't spaces or quotes, and sequences of characters that begin and end with a quote, with no quotes in between, for two kinds of quotes. You can easily match those things with this regular expression:

    [^\s"']+|"([^"]*)"|'([^']*)'
    

    I added the capturing groups because you don't want the quotes in the list.

    This Java code builds the list, adding the capturing group if it matched to exclude the quotes, and adding the overall regex match if the capturing group didn't match (an unquoted word was matched).

    List<String> matchList = new ArrayList<String>();
    Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        if (regexMatcher.group(1) != null) {
            // Add double-quoted string without the quotes
            matchList.add(regexMatcher.group(1));
        } else if (regexMatcher.group(2) != null) {
            // Add single-quoted string without the quotes
            matchList.add(regexMatcher.group(2));
        } else {
            // Add unquoted word
            matchList.add(regexMatcher.group());
        }
    } 
    

    If you don't mind having the quotes in the returned list, you can use much simpler code:

    List<String> matchList = new ArrayList<String>();
    Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group());
    } 
    
    0 讨论(0)
  • 2020-11-22 03:35

    There are several questions on StackOverflow that cover this same question in various contexts using regular expressions. For instance:

    • parsings strings: extracting words and phrases
    • Best way to parse Space Separated Text

    UPDATE: Sample regex to handle single and double quoted strings. Ref: How can I split on a string except when inside quotes?

    m/('.*?'|".*?"|\S+)/g 
    

    Tested this with a quick Perl snippet and the output was as reproduced below. Also works for empty strings or whitespace-only strings if they are between quotes (not sure if that's desired or not).

    This
    is
    a
    string
    that
    "will be"
    highlighted
    when
    your
    'regular expression'
    matches
    something.
    

    Note that this does include the quote characters themselves in the matched values, though you can remove that with a string replace, or modify the regex to not include them. I'll leave that as an exercise for the reader or another poster for now, as 2am is way too late to be messing with regular expressions anymore ;)

    0 讨论(0)
  • 2020-11-22 03:35

    I'm reasonably certain this is not possible using regular expressions alone. Checking whether something is contained inside some other tag is a parsing operation. This seems like the same problem as trying to parse XML with a regex -- it can't be done correctly. You may be able to get your desired outcome by repeatedly applying a non-greedy, non-global regex that matches the quoted strings, then once you can't find anything else, split it at the spaces... that has a number of problems, including keeping track of the original order of all the substrings. Your best bet is to just write a really simple function that iterates over the string and pulls out the tokens you want.

    0 讨论(0)
  • 2020-11-22 03:36

    The following returns an array of arguments. Arguments are the variable 'command' split on spaces, unless included in single or double quotes. The matches are then modified to remove the single and double quotes.

    using System.Text.RegularExpressions;
    
    var args = Regex.Matches(command, "[^\\s\"']+|\"([^\"]*)\"|'([^']*)'").Cast<Match>
    ().Select(iMatch => iMatch.Value.Replace("\"", "").Replace("'", "")).ToArray();
    
    0 讨论(0)
提交回复
热议问题