getting value inside double quotes , preceded by a word

问题内容:

I’m thinking to do two regex for get $price and then 33fff50.00 in this string:

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

both regex are preceded for ‘Variable’ and ‘value’ word:

I’ve tried:

\b[Variable ]"(.*)"

but it’s not working

问题评论:

    
both regex are preceded for ‘Variable’ and ‘value’ word: And both are wrapped in double quotes. Can you just extract values in double quotes?
    
not really, need to find the word inside quotes preceding the key, because the string can have a lot of double quotes after, it’s a long string
– DDave
5 hours ago
1  
You might want to look up what square brackets mean in a regex
1  
\bVariable "(.*?)"

答案:

答案1:

If variable and value are fixed strings with special meaning, then try

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

Demo

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] );
}

答案评论:

    
very nice, it’s working, just I delete ‘$’ with .replace() , maybe is a way to delete ‘$’ with regex?
– DDave
1 hour ago

答案2:

One way to do it would be

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

Broken down this says:

\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

Here, you need to take group 1 and 2, see a demo on regex101.com.


Additionally, \b[Variable ] does not do what you think it does. It’ll look for one of V, a, r, i, a, b, l, e.

答案评论:

原文地址:

https://stackoverflow.com/questions/47750826/getting-value-inside-double-quotes-preceded-by-a-word

添加评论

友情链接:蝴蝶教程