首页 > 解决方案 > 替换除第 3 次以外的所有匹配项

问题描述

我正在扫描二维码,需要一个脚本来用 (\t) 替换逗号

我的结果是:

820-20171-002,,2020 年 11 月 24 日,,,13,283.40,,Mike Shmow

我的问题是 - 我不想在日期之后使用逗号。现在我有以下内容 - 它可以用制表符替换逗号。

decodeResults[0].content.replace(/,/g, "\t");

我正在尝试用表达式替换 /,/g 以替换除第 3 次出现的所有逗号。

标签: regexreplace

解决方案


利用

.replace(/(?<!\b[a-zA-Z]{3}\s+\d{1,2}(?=,\s*\d{4})),/g, '\t')

证明

解释

--------------------------------------------------------------------------------
  (?<!                      Negative lookbehind start, fail if pattern matches
--------------------------------------------------------------------------------
    \b                       the boundary between a word char (\w)
                             and something that is not a word char
--------------------------------------------------------------------------------
    [a-zA-Z]{3}              any character of: 'a' to 'z', 'A' to 'Z'
                             (3 times)
--------------------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    \d{1,2}                  digits (0-9) (between 1 and 2 times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
      ,                        ','
--------------------------------------------------------------------------------
      \s*                      whitespace (\n, \r, \t, \f, and " ")
                               (0 or more times (matching the most
                               amount possible))
--------------------------------------------------------------------------------
      \d{4}                    digits (0-9) (4 times)
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
  )                        end of negative lookbehind
--------------------------------------------------------------------------------
  ,                        ','

推荐阅读