Home > front end >  Regex: match for dollar value between two strings with different context
Regex: match for dollar value between two strings with different context

Time:01-19

It will cost you $112.52 for 302 pokemon cards to complete this order

It will cost you $112.52 to complete this order

Above are two strings that I want to find the dollar value using regex. Below is my current regex:

const match = str.match(/will cost you \$(.*) for ([0-9] ) pokemon cards to complete this order|will cost you \$(.*) to complete this order/);

I can get $112.52 in match[1] and match[3] for both strings.

However with this way (([0-9] )), I am also matching the number of pokemon cards 302 which is NOT what I want (in match[2]). Is there a way I can ignore any number of pokemon cards and match just the dollar sign value in both strings in a single regex?

CodePudding user response:

If you just want the dollar amount and don't care about anything else in the string, you don't need to mention anything else in the string in your regex.

You could just match $ followed by numbers and dots, i.e

str.match(/\$([\d\.] )/)

A fuller test example...

(function() {
    let strs = [
        "It will cost you $112.52 for 302 pokemon cards to complete this order",
        "It will cost you $112.52 to complete this order"
    ];
    
    strs.forEach(
        (str) => {
            let match = str.match(/\$([\d\.] )/);
            console.debug(match);
        }
    );
})();

...outputs...

Array [ "$112.52", "112.52" ]
Array [ "$112.52", "112.52" ]

CodePudding user response:

Have you tried your regex on https://regex101.com/ ?

I found this solution after trying this website :

(will cost you $(.) for ([0-9] ) pokemon cards to complete this order|will cost you $(.) to complete this order)

It will put your price into group2 and the number of cards into group 3

CodePudding user response:

use lookbehind assertion in regex

(?<=Y)X Positive lookbehind X if after Y

(?<=\$)\d

example: https://regex101.com/r/H7Iyb6/1

reference: https://javascript.info/regexp-lookahead-lookbehind

  • Related