英文:
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 = [
'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' : ''
)
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论