Split a string by whitespace, keeping quoted segments, allowing escaped quotes

前端 未结 4 1932
南方客
南方客 2020-11-28 09:27

I currently have this regular expression to split strings by all whitespace, unless it\'s in a quoted segment:

keywords = \'pop rock \"hard rock\"\';
keyword         


        
4条回答
  •  孤独总比滥情好
    2020-11-28 09:50

    You can change your regex to:

    keywords = keywords.match(/\w+|"(?:\\"|[^"])+"/g);
    

    Instead of [^"]+ you've got (?:\\"|[^"])+ which allows \" or other character, but not an unescaped quote.

    One important note is that if you want the string to include a literal slash, it should be:

    keywords = 'pop rock "hard rock" "\\"dream\\" pop"'; //note the escaped slashes.
    

    Also, there's a slight inconsistency between \w+ and [^"]+ - for example, it will match the word "ab*d", but not ab*d (without quotes). Consider using [^"\s]+ instead, that will match non-spaces.

提交回复
热议问题