我有一个这样的字符串:
var a = "expect ${} to any text ${}"
a = "expect ${} to include text ${}"
a = "expect ${} to deepEqual text ${}"
我想获取字符串中to
旁边的值。例如,那应该给我:
any
include
deepEqual
我应该如何在javascript中执行此操作?
答案 0 :(得分:1)
我没有正则表达式专家,但这很有效,正则表达式为/ to (\w+)/
:
var a = "expect ${} to any text ${}";
console.log(a.match(/ to (\w+)/)[1]); // any
a = "expect ${} to include text ${}";
console.log(a.match(/ to (\w+)/)[1]); // include
a = "expect ${} to deepEqual text ${}";
console.log(a.match(/ to (\w+)/)[1]); //deepEqual
答案 1 :(得分:1)
试试这个: .*(?:\bto\b)\s+(\w+).*
var re = /.*(?:\bto\b)\s+(\w+).*/gm;
var str = 'var a = "expect ${} to any text ${}"\na = "expect ${} to include text ${}"\na = "expect ${} to deepEqual text ${}"';
var subst = '$1';
var result = str.replace(re, subst);
<强> Live demo 强>
答案 2 :(得分:0)
您不需要正则表达式。只拆分两次
var str = "expect ${} to any text ${}";
console.log(str.split("to")[1].split(" ")[1]);
我们首先拆分to
所以它会导致
["expect ${} ", " any text ${}"]
然后我们将第二个元素和" "
分开,这将导致
["", "any", "text", "${}"] // take second element from here
如果你真的想要正则表达式,那么第一组将包含文本/to\s*(\S+)/
。