我有以下表达式:
where('publishedDate').gte(new Date('2015-08-21T20:37:45.176Z')).sort({ field: 'asc', test: -1 });
我想用javascript的string :: split(regex)解析下面的标记:
where
('publishedDate')
gte
(new Date('2015-08-21T20:37:45.176Z'))
sort
({ field: 'asc', test: -1 })
但是我很难想出一个合适的表达方式。非常感谢任何帮助!
答案 0 :(得分:2)
你可以使用这个:
/(\w+)(\(.+?\)(?=\.|;|$))/g
它适用于您的输入。
演示:https://regex101.com/r/kV9lS4/1
var re = /(\w+)(\(.+?\)(?=\.|;))/g,
str = "where('publishedDate').gte(new Date('2015-08-21T20:37:45.176Z'))" +
".sort({ field: 'asc', test: -1 });",
result = [],
arr;
while(arr = re.exec(str)) {
result.push(arr[1]);
result.push(arr[2]);
}
var re = /(\w+)(\(.+?\)(?=\.|;))/g,
str = "where('publishedDate').gte(new Date('2015-08-21T20:37:45.176Z')).sort({ field: 'asc', test: -1 });",
result = [],
arr;
while(arr = re.exec(str)) {
result.push(arr[1]);
result.push(arr[2]);
}
document.getElementById('result').innerHTML = JSON.stringify(result, null, 2);

<pre id="result"></pre>
&#13;