我应该用空格(或\ r \ n \ t)分割一个可能包含子串的字符串
例:
text 'contained in' a string我试过像正则表达式:
/[?<!\"\'](\ )*[?!\"\']/g;string.split(regex)应该返回:
["text", "'contained in'", "a", "string"]。
但这是错的......我在很长时间内解决这个问题:@
现在,我创建了一个split函数,如果有超出子串的话,会自动用sepchar分割,但是我正在寻找一个带正则表达式的简单解决方案,如果可能的话,显然:P
I should split by spaces (or \r\n\t) a string that could contains substrings
Example:
text 'contained in' a stringI have tried with a regex like:
/[?<!\"\'](\ )*[?!\"\']/g;string.split(regex) should returns:
["text", "'contained in'", "a", "string"].
But it's wrong... I'm freaking from much time to resolve it :@
For now, I made a split function that automatically split by a sepchar if there are out of substrings, but I'm looking for a simple solution with regex, if possible, obviously :P
最满意答案
你可以这样做:
(?:'(.*)'|(\b[\w]+\b))工作正则表达式示例:
http://regex101.com/r/oJ2nQ9
或者甚至更好,而不是使用单词bounderies(因为你的字符串可能包含特殊字符)..这会更好:
(?:'(.*?)'|(?:[\s]*|^)([^\s]+)(?:[\s]*|$))样本字符串:
text 'contained in' a string-with special's chars.火柴:
"text", "contained in", "a", "string-with", "special's", "chars."工作正则表达式示例:
http://regex101.com/r/iP3iJ1
You could do this:
(?:'(.*)'|(\b[\w]+\b))Working regex example:
http://regex101.com/r/oJ2nQ9
Or even better, rather than using word bounderies (because your string may contain special characters).. This would be better:
(?:'(.*?)'|(?:[\s]*|^)([^\s]+)(?:[\s]*|$))Sample string:
text 'contained in' a string-with special's chars.Matches:
"text", "contained in", "a", "string-with", "special's", "chars."Working regex example:
http://regex101.com/r/iP3iJ1
更多推荐
发布评论