markdown 货币正则表达式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 货币正则表达式相关的知识,希望对你有一定的参考价值。

<h1>The RegEx</h1>

```
// Requires a decimal and commas
^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{1,2}$

// Allows a decimal, requires commas
(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$

// Decimal and commas optional
(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$

// Decimals required, commas optional
^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{1,2}$

// *Requires/allows X here also implies "used correctly"
```

## The RegEx Breakdown

- When the optional parts are too liberal, we need to look ahead and guarantee there's a number: `(?=.*\d)`
- May or may not start with a dollar sign (I assume negatives are invalid): `^\$?`
  - Follow that with `-?` to allow negative numbers
- Begins with 1-3 numbers: `[1-9]\d{0,2}`
  - Could almost be `(\d{1,3})`, but that would allow "0,123"
  _ One exception, can start with 0 in the case of "$0.50" or "0.50": `|0`
  _ These regexes assume multiple leading 0's are invalid
- Any number of three digit numbers separated by comma: `(,\d{3})*`
  - Remove `?` before `\.` if you want to disallow numbers starting with "$."
- Requires or allows decimal (one or two digits): `\.\d{1,2}` or `(\.\d{1,2})?` respectively
_ End with `$` (unescaped) to make sure there's nothing after a valid number (like $1,000.00b)

To use the regex, use the string's `match` method and encase the regex between two forward slashes.

```
// The return will either be your match or null if not found
yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);

// For just a true/false response
!!yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);
```

以上是关于markdown 货币正则表达式的主要内容,如果未能解决你的问题,请参考以下文章

负会计货币价值的正则表达式?

正则表达式仅匹配美元符号、货币、小数

如何使用正则表达式将数字格式化为货币

印度卢比货币的正则表达式'₹'

Javascript 正则表达式替换所有非货币字符

如何编写正则表达式模式以匹配字符串结尾或字符串开头的货币符号