【问题标题】:Javascript Regular expression for currency amount with spaces带有空格的货币金额的Javascript正则表达式
【发布时间】:2014-07-04 07:33:26
【问题描述】:

我有这个正则表达式

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

它与 $55.5 非常匹配,但在我的少数测试数据中,我有一些值,例如 $55.5(我的意思是,它在 $ 符号后有一个空格)。

此链接上的答案对我不起作用。 Currency / Percent Regular Expression

那么,我怎样才能改变它来接受空格呢?

【问题讨论】:

  • ([£,$,€]?\d+ 更改为([£,$,€]?\s*\d+
  • 正则表达式看起来太长了……
  • 这是一个非常笨拙的正则表达式,您要精确匹配什么?
  • 字符类中不需要逗号来分隔字符,如果要加逗号,一次就够了。逗号也不需要转义。在字符类中,您只需要转义 -]

标签: javascript regex currency


【解决方案1】:

尝试关注RegEx

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

让我知道它是否有效!

Demo Here

【讨论】:

  • 这将匹配,, 123,456789$ %
  • 为什么要在答案中保留原始正则表达式中的明显错误?
【解决方案2】:

TLDR:

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

科学位

好的,我猜你没有构造原始的正则表达式,所以这里是它的部分,并标记了添加:

^ # match from the beginning of the string
[',",\+,<,>,\(,\*,\-,%]?    # optionally one of these symbols
(                           # start a group
   [£,$,€]?                   # optionally one of these symbols
   \s*                        # <--- NEW ADDITION: optionally one or more whitespace
   \d+                        # then one or more decimal digits
   (                          # start group 
      [\,,\.]                   # comma or a dot
      \d+                       # then one or more decimal digits
   )?                         # group optional (comma/dot and digits or neither)
   [£,$,€]?                   # optionally one of these symbols
   \s*                        # optionally whitespace
   [\-,\/,\,,\.,\+]?          # optionally one of these symbols
   [\/]?                      # optionally a /
   \s*                        # optionally whitespace
)+                          # this whole group one or more times
[',",\+,   <,>,\),\*,\-,%]? # optionally one of these symbols
$ # match to the end of the string

其中大部分是关于匹配货币金额的东西,所以你可以减少它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多