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

后端 未结 15 2138
梦毁少年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: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 ;)

提交回复
热议问题