开发者

Regular Expression - extract digits

I have strings of text that may have the following 开发者_运维问答formats:

Was £39.95 Now Only £29.00

OR

Was 0.95p Now 10p

What is the easiest way to extract two numbers from each string, so I can subtract them later.


This monstrosity will capture two numbers separated by text. It will also capture the units.

$match = preg_match("/((?:£)?(\d+(?:\.\d+)?)(?:p)?)[a-z\s]*((?:£)?(\d+(?:\.\d+)?)(?:p)?)/i", "Was £39.95 Now Only 99p");

print_r($matches);

This will yield:

Array (
    [0] => Was £39.95 Now Only 99p
    [1] => £39.95
    [2] => 39.95
    [3] => 99p
    [4] => 99
)


You can use a regular expression like the following:

/\d+(\.\d+)?/

Be careful because this won't read the units, so you could easily end up with an error if there is something like the following:

Was £2 Now Only 99p 

You may also want to watch out for commas in your text string. Note that there are also internationalization issues here that you should be aware of. Many countries use , as a decimal separator and . as the thousands separator. You might be able to guess the locale from the currency (e.g. £ suggests that the decimal separator is .).

If you can be more precise about what sort of values your program must accept then you will probably get better answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜