如何改进正则表达式?

How to improve the regex?

我正在尝试将以下可能性与正则表达式相匹配:

MORE THAN CAD 10,000
MORE THAN CAD 10,000 BUT LESS THAN CAD 15,000
LESS THAN CAD 10,000

我的正则表达式适用于 /^(((MORE|LESS) THAN CAD [\d,]+)|(MORE THAN CAD [\d,]+ BUT LESS THAN CAD [\d,]+))$/,但我想知道是否有更优雅的方式。

我试过 /^(MORE THAN CAD [\d,]+)?(( BUT )?LESS THAN CAD [\d,]+)?$/ 但它也让以下内容通过:

MORE THAN CAD 10,000LESS THAN CAD 15,000

您可以使用

^(?:(MORE)|LESS) THAN CAD [\d,]+(?(1)(?: BUT LESS THAN CAD [\d,]+)?)$

参见regex demo

详情:

  • ^ - 字符串开头
  • (?:(MORE)|LESS) - 匹配 MORE(在第 1 组中捕获)或 LESS
  • 的非捕获组
  • THAN CAD - 文字字符串
  • [\d,]+ - 一位或多位数字或逗号
  • (?(1)(?: BUT LESS THAN CAD [\d,]+)?) - 如果第 1 组匹配,允许匹配可选 BUT LESS THAN CAD [\d,]+ 模式的条件。
  • $ - 字符串结尾。