在双引号内获取值,前面有一个单词

时间:2017-12-11 10:26:53

标签: javascript regex

我打算用两个正则表达式获得$ price,然后在此字符串中输入33fff50.00:

Variable "$price" got invalid value "33fff50.00"

两个正则表达式都以“变量”和“值”字开头:

我试过了:

\b[Variable ]"(.*)"

但它不起作用

2 个答案:

答案 0 :(得分:1)

一种方法是

\bVariable[^"]+"([^"]+)"[^"]+"([^"]+)"

细分说:

\b        # word boundary
Variable  # Variable literally
[^"]+     # not a double quote, 1+ times
"([^"]+)" # capture anything between double quotes into group 1
[^"]+     # same as above
"([^"]+)" # group 2

在这里,您需要进行第1组和第2组,请参阅a demo on regex101.com

<小时/> 此外,\b[Variable ]没有按照您的想法执行。它会查找Varia,{{1}的一个 },bl

答案 1 :(得分:0)

如果variablevalue是具有特殊含义的固定字符串,请尝试

var matches = str.match( /variable\s+\"(.*)".*value\s+\"(.*)\"/i )
if (matches)
{
   console.log( "variable ", matches[1] );
   console.log( "value ", matches[2] );
}

<强>演示

var str = 'Variable "$price" got invalid value "33fff50.00"';
var matches = str.match( /variable\s+\"(.*)".*value\s+\"(.*)\"/i )
if (matches)
{
   console.log( "variable ", matches[1] );
   console.log( "value ", matches[2] );
}