RegEx - How to Extract Price?

前端 未结 5 570
名媛妹妹
名媛妹妹 2020-12-06 19:19

How would I extract the dollar amount from the following string

\"some text will go here and more and more and then there will be some price $34.03 but that doesn\'t

相关标签:
5条回答
  • 2020-12-06 19:34

    What about this regexp: \$[0-9.,]+ or \$([0-9.,]+) to strip the $?

    It's simple but it does pretty much what you want, it even catches things like this: $1,450.8934 or $14.343.

    Of course the drawback it'd be that it'd catch $34.54.23 as well.

    Or if you want to catch only two decimals: \$[0-9,]+\.[0-9]{2} it'd catch the $5.23 part of $5.234565.

    You can use it with preg_match or preg_match_all.

    0 讨论(0)
  • 2020-12-06 19:37

    Since you don't mention a specific regex engine, you might have to adjust this a bit:

    /(\$\d+(\.\d+)?)/
    
    0 讨论(0)
  • 2020-12-06 19:43

    I'm no regex-guru, but was able to whip up the following with RegExr.

    /(\$[0-9]+(\.[0-9]{2})?)/
    

    Matches $35.03 and $35. To accept formats like $35,000.52 you would need to include ,

    /(\$[0-9,]+(\.[0-9]{2})?)/
    

    This could likely be improved upon, but from my preliminary tests, it works just fine.

    0 讨论(0)
  • 2020-12-06 19:51
    '/\$\d+(?:\.\d+)?/'
    
    if(preg_match('/\$\d+(?:\.\d+)?/',$text,$matches)){
        echo $matches[0]; //which would be $34 or $34.03
    }
    
    0 讨论(0)
  • 2020-12-06 19:56

    I am currently working on a small function using regex to get price amount inside a String :

    private static String getPrice(String input)
    {
        String output = "";
    
        Pattern pattern = Pattern.compile("\\d{1,3}[,\\.]?(\\d{1,2})?");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find())
        {
            output = matcher.group(0);
        }
    
        return output;
    }
    

    this seems to work with small price (0,00 to 999,99) and various currency :

    $12.34 -> 12.34

    $12,34 -> 12,34

    $12.00 -> 12.00

    $12 -> 12

    12€ -> 12

    12,11€ -> 12,11

    12.999€ -> 12.99

    12.9€ -> 12.9

    £999.99€ -> 999.99

    ...

    0 讨论(0)
提交回复
热议问题