正则表达式检查数字系统

huangapple go评论67阅读模式
英文:

Regular expression to check number system

问题

正则表达式匹配数字系统1:

/^\d+(?:,\d{3})*(?:\.\d+)?$/

正则表达式匹配数字系统2:

/^\d+(?:\.\d{3})*(?:,\d+)?$/

正则表达式匹配数字系统3:

/^\d+(?:[ ,]\d{3})*(?:\.\d+)?$/

这些正则表达式可以用于匹配不同数字系统的数字,包括千位分隔符和小数点。

英文:

I am working on an application that takes numbers and converts them to the locale format. In order to do so I must first identify which locale the entered number belongs to format it accordingly.

Therefore, can anybody please provide Regex to match which number system the given number belongs too?

Example:

Regex for number system 1:

  • 1 // should match
  • 10 // should match
  • 1000 //should match
  • 1000.00 //should match
  • 1,000.00 //should match

And so on..

Regex for number system 2:

  • 1 // should match
  • 10 // should match
  • 1000 // should match
  • 1.000 // should match
  • 1.000,00 // should match

And so on..

Regex for number system 3:

  • 1 // should match
  • 10 // should match
  • 1000 // should match
  • 1 000 // should match
  • 1 000.00 // should match.

And so on..

So far I have written this: /^\d*[,]?\d*\.?\d+$/ But this doesn't work if there are more than one thousand separators. Example: 10,00,000.00

I basically need three regex to check which of the 3 widely used number system the entered number belongs to.

答案1

得分: 1

const commaDot = /^(?:\d{0,3}(?:,\d{3})|\d+)(?:\.\d+)?$/
const dotComma = /^(?:\d{0,3}(?:.\d{3})|\d+)(?:,\d+)?$/
const spaceDot = /^(?:\d{0,3}(?: \d{3})|\d+)(?:.\d+)?/

const cases = [
  '1',
  '10',
  '1000',
  '1000.00',
  '1,000.00',

  '1',
  '10',
  '1000',
  '1000,00',
  '1.000,00',

  '1',
  '10',
  '1000',
  '1000.00',
  '1 000.00',
]

for (const cas of cases) {
  console.log(
    cas,
    'matches:',
    cas.match(commaDot) ? '1' : '',
    cas.match(dotComma) ? '2' : '',
    cas.match(spaceDot) ? '3' : ''
  )
}
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const commaDot = /^(?:\d{0,3}(?:,\d{3})|\d+)(?:\.\d+)?$/
const dotComma = /^(?:\d{0,3}(?:\.\d{3})|\d+)(?:,\d+)?$/
const spaceDot = /^(?:\d{0,3}(?: \d{3})|\d+)(?:\.\d+)?$/

const cases = [
  &#39;1&#39;,
  &#39;10&#39;,
  &#39;1000&#39;,
  &#39;1000.00&#39;,
  &#39;1,000.00&#39;,

  &#39;1&#39;,
  &#39;10&#39;,
  &#39;1000&#39;,
  &#39;1000,00&#39;,
  &#39;1.000,00&#39;,

  &#39;1&#39;,
  &#39;10&#39;,
  &#39;1000&#39;,
  &#39;1000.00&#39;,
  &#39;1 000.00&#39;,
]

for (const cas of cases) {
  console.log(
    cas,
    &#39;matches:&#39;,
    cas.match(commaDot) ? &#39;1&#39; : &#39;&#39;,
    cas.match(dotComma) ? &#39;2&#39; : &#39;&#39;,
    cas.match(spaceDot) ? &#39;3&#39; : &#39;&#39;
  )
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 04:20:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定