标记由1个或多个空格分隔。带引号的字符串是一个单独的令牌。任何其他不以引号开头的内容都是令牌。我尝试了一下,但失败了:
var tokenre = /"[^"]*"|[^"]\S+|\s\s*/g;
例如,我想要以下输入
[4,4] "This is fun"
2 2 +
#
标记化为
['[4,4]', ' ', '"This is fun"', '\n ', '2', ' ', '2', ' ', '+', '\n ', '#']
这可以使用以下代码进行测试:
var result = null;
do {
result = tokenre.exec (program);
console.log (result);
} while (result != null);
发布于 2018-07-18 05:03:46
您似乎希望将字符串标记为空格和非空格字符块,但也要将引号之间的子字符串之类的"..."
分隔为单独的元素。
您可以使用以下命令来实现它
s.match(/"[^"]*"|\S+|\s+/g)
请参阅regex demo。
详细信息
"[^"]*"
-一个空格,然后是除引号之外的任何空格字符,最后是一个空格(注意:为了匹配常规转义序列,您需要用chars|
- or\s+
- 1+非空格字符替换它。JS demo:
var s = "[4,4] \"This is fun\"\n2 2 +\n#";
console.log(s.match(/"[^"]*"|\S+|\s+/g));
https://stackoverflow.com/questions/51387601
复制相似问题