最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regexp for European price - Stack Overflow

programmeradmin2浏览0评论

I tested the following regexp for US prices (delimiter ma, separator dot) which is running fine:

 ^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(\.[0-9]{2})?$

It works, prices like 30,000.000 are refused. Only 2 decimals are accepted.

I tried to exchange them for handling European prices:

^[1-9][0-9]{0,2}(?:.?[0-9]{3}){0,3}(\,[0-9]{2})?$

but it does not work, prices like 30.000,000 are accepted, which is wrong. Only 2 decimals should be accepted.

What's wrong in these 2 regexps?

I tested the following regexp for US prices (delimiter ma, separator dot) which is running fine:

 ^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(\.[0-9]{2})?$

It works, prices like 30,000.000 are refused. Only 2 decimals are accepted.

I tried to exchange them for handling European prices:

^[1-9][0-9]{0,2}(?:.?[0-9]{3}){0,3}(\,[0-9]{2})?$

but it does not work, prices like 30.000,000 are accepted, which is wrong. Only 2 decimals should be accepted.

What's wrong in these 2 regexps?

Share Improve this question edited Feb 22, 2012 at 21:32 pimvdb 155k80 gold badges311 silver badges356 bronze badges asked Feb 22, 2012 at 21:30 user762579user762579 1
  • F.J's answer is correct. Just a side, the first regex for US would allow for a value like this: 900,000000,000.00 that is Nine-hundred-million-thousand dollars. Probably correct, but sounds kind of funny. If a ma is included, you could force it to be used every 3rd decimal, or optionally accept all digits using this: ^[1-9][0-9]{0,2}(?:(?:,[0-9]{3}){1,3}|[0-9]{1,9})?(?:\.[0-9]{2})?$. – user557597 Commented Feb 22, 2012 at 23:22
Add a ment  | 

1 Answer 1

Reset to default 8

In regex, . is a special character so when you want to match a literal dot you need to escape it with a backslash (\.). This is not the case for mas, so you can leave them unchanged.

In your attempt you switched the , and the . which left you with an unescaped . and a \, at the end, when you actually want to switch the , and the \. like this:

^[1-9][0-9]{0,2}(?:\.?[0-9]{3}){0,3}(,[0-9]{2})?$
发布评论

评论列表(0)

  1. 暂无评论