Regular expression to check number system - javascript

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.

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' : ''
)
}

Related

Regular expression to insert dash into numbers after 3 and 4 digits

I'm trying to insert dash into numbers but it is so hard to me...
What I want to do is that insert dash into after 3 and 4 digits, for example,
replacing 123123412345 to 123-1234-12345.
The additional condition is that I replace it in input element. So I replace the number for every input event, i.e., I need to replace like
1 to 1
12 to 12
123 to 123
1231 to 123-1
...
1231234 to 123-1234
12312341 to 123-1234-1
...
123123412345 to 123-1234-12345
How can I do this using regex ??
You may try this regex:
Regex
(?<=^\d{3}|^\d{7})(?=\d)
Substitution
-
Check the proof
const list = [
1,
12,
123,
1231,
1231234,
12312341,
123123412345
];
const regex = /(?<=^\d{3}|^\d{7})(?=\d)/g;
const result = list.map(e => regex[Symbol.replace](e, '-'));
console.log(result);
Suppose it needs to split the first 3 next 4 digits only, it can be done with following regexp replacement
str.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')
Input string has to be all digits
document.getElementById('input').addEventListener('keyup', (e) => {
e.target.value = e.target.value.split('-').join('').replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-');
});
['1', '12', '123', '1231', '12312', '123123', '1231234', '12312341', '123123412', '1231234123', '12312341234', '123123412345']
.forEach(t => console.log(t.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')));
<input id="input" type="text" size="20">

match pattern nth digit of a number using regex

I am using a regex /^(\+88)?01[3-9]\d{8}$/
let phoneNum = "+880136486336"
let validRegex = /^(\+88)?01[3-9]\d{8}$/;
console.log(validRegex.test(phoneNum));
to match a pattern that matches some strings like
+8801712345678
01712345678
01312349876
It works fine but I also want to match 01[n] where n will be 3-9. pattern to find out the mobile network operator.
I want to do something like this
if the number is 01712345678 then print "Network Operator A",
if the number is +8801712345678 then print "Network Operator A"
if the number is 01312349678 then print "Network Operator B"
and different operators for different values of n.
here 017, 013, 014, 016, 015, 019, 018 are mobile operator codes which I want to use to find out operator based on the mobile number.
I don't find any way to do it.
How can I do it with regex?
You can capture the three digits at the start with a capturing group, then use String#match or RegExp#exec to get the actual match and then, if there is a match, get the group value and obtain the operator name from a dictionary:
const phones = ['+8801712345678','01712345678','01312349876'];
const operators = {'017' : 'Operator A', '013' : 'Operator C', '014' : 'Operator B', '016' : 'Operator D', '015' : 'Operator E', '019' : 'Operator F', '018' : 'Operator G'};
const validRegex = /^(?:\+88)?(01[3-9])\d{8}$/;
for (const phone of phones) {
const match = validRegex.exec(phone);
if (match) {
console.log(phone, "=> Valid, belongs to", operators[match[1]])
} else {
console.log(phone,"=> NO MATCH");
}
}
Here,
^(?:\+88)?(01[3-9])\d{8}$: the first optional group is now non-capturing and there is a capturing group with ID = 1 now, (01[3-9])
validRegex.exec(phone) gets the match object
operators[match[1]] returns the Operator name by the key.

Regex pattern validation for variable number of number pairs

I am trying to verify that a string is in the correct format...
Number pairs, seperated by a hyphen, each number with a max of 3 digits
No negative numbers
Pairs are seperated by a |
Pattern:
XXX-XXX
XXX-XXX|XXX-XXX|...
Example valid input:
var string1 = "18-200"; // Single entry
var string2 = "18-200|36-90"; // Multiple entries
Example invalid input:
var string3 = "18-2000"; // Failed because the second number has 4 digits
var string4 = "1-1-1-1"; // Failed because there are 4 alternatives, not 2
var string5 = "-20-100"; // Failed because it starts with a negative
I've come up with the following pattern:
^[0-9]+(-[0-9]+)+$
But the expression doesn't match all of the criteria, for example 1-1-1-1 is still okay.
Assuming that:
You always match from the start of the supplied string to the end
You always match in pairs like XXX-XXX
Multiple pairs are separated by |
Then we could write a simplified regex...
^\d-\d(\|\d-\d)*$
Which we can then expand to arrive at...
^\d{1,3}-\d{1,3}(?:\|\d{1,3}-\d{1,3})*$
^ : Start of string
\d{1,3} : Match a number 1 to 3 times
- : Match literally
\d{1,3} : Match a number 1 to 3 times
(?: : Start of non-capturing group
\| : Match literally
\d{1,3} : Match a number 1 to 3 times
- : Match literally
\d{1,3} : Match a number 1 to 3 times
) : End of group
* : Quantifier for 0 or more occurrences of the non-capturing group
$ : End of string
Which we can then test in JS using match to verify...
var regex = /^\d{1,3}-\d{1,3}(?:\|\d{1,3}-\d{1,3})*$/;
var testStrings = [
`1-12`,
`1-12|88-100`,
`1-12|88-100|1-111`,
`1-1-1-1`,
`1-12|`,
`1-12|1-1-2`,
];
for (let num in testStrings) {
console.log(testStrings[num].match(regex));
}
Output, as expected:
["1-12", index: 0, input: "1-12", groups: undefined]
["1-12|88-100", index: 0, input: "1-12|88-100", groups: undefined]
["1-12|88-100|1-111", index: 0, input: "1-12|88-100|1-111", groups: undefined]
null
null
null
One possible approach (for each number up to 3 digits):
^[0-9]{1,3}-[0-9]{1,3}(?:\|[0-9]{1,3}-[0-9]{1,3})*$
Regex101 demo. Essentially, you just repeat the first part of the pattern, preceding it with escaped |, then (with *) make sure the whole group is repeated - or not.
Escaping is important, as | is a metacharacter. And when you use this string in Angular Validator (as it somehow turned out), you should escape the escaping character (\) in your string literal, so it becomes...
requiredPattern: "^[0-9]{1,3}-[0-9]{1,3}(?:\\|[0-9]{1,3}-[0-9]{1,3})*$"

How do I match components in a string math expression with unknown digits in javascript?

So I have this data array which contains math expressions as strings.
var data = ['1+1=?', '123*45?=5?088', '-5?*-1=5?', '19--45=5?', '??*??=302?', '?*11=??', '??*1=??', '??+??=??']
The question marks indicate an unknown digit, so it's part of a number. How do I split them up so that I have factors/addends, the operation, and the answer on the right side of the equation stored in an array?
This is the result that I want to get:
'1+1=?' ---> ['1', '+', '1', '?']
'123*45?=5?088' ---> ['123', '*', '45?' '5?088']
'-5?*-1=5?' ---> ['-5?', '*', '-1', 5?']
'19--45=5?' ---> ['19', '-', '-45', '5?']
'??*??=302?' ---> ['??', '*', '??', '302?']
'?*11=??' ---> ['?', '*', '11', '??']
'??*1=??' ---> ['??', '*', '1', '??']
'??+??=??' ---> ['??', '+', '??', '??']
It's tricky for me especially the one where there's a subtraction with a negative number.
Thanks in advance!
You may try this regex:
-?[\d?]+|[^=]
-?[\d?]+: any combination of digits and ? with an optional leading -.
|: or
[^=]: something not a =
Check the test cases
const texts = [
'1+1=?',
'123*45?=5?088',
'-5?*-1=5?',
'19--45=5?',
'??*??=302?',
'?*11=??',
'??*1=??',
'??+??=??'
];
const regex = /-?[\d?]+|[^=]/g;
const groups = texts.map(text => text.match(regex));
console.log(groups);
Edit
If the format is consistant, you may try this regex to get each part of the equation:
(-?[\d?]+)([^=\d?])(-?[\d?]+)=(-?[\d?]+)
See the test cases
const texts = [
'1+1=?',
'123*45?=5?088',
'-5?*-1=5?',
'19--45=5?',
'??*??=302?',
'?*11=??',
'??*1=??',
'??+??=??',
'?33438-103326=410112'
];
const regex = /^(-?[\d?]+)([^=\d?])(-?[\d?]+)=(-?[\d?]+)$/;
const groups = texts.map(text => text.match(regex).splice(1));
console.log(groups);

Javascript regex that matches one pattern in string but exclude another

I have two possible strings that I need to match:
+/-90000
and
+9000 / -80000
I need to recognise the two patterns separately so wrote some regex for this. The first single number string I can match like so:
/\+\/\-{1}/g
And i wrote this for the second:
/(\+(?=[0-9]+){1}|\-(?=[0-9]+){1}|\/(?=\s){1})/g
The second would also partially match the first the first number i.e. the -90000. Is there a way that they can be improved so that they match exclusively?
You can use a single expression:
^(?:(\+\/-\s*\d+)|((\+\s*\d+)\s*\/\s*(-\s*\d+)))$
The only restriction you'll have to work with would be that in the second type of input, the positive number should come first.
You'll get the matched group in matches[1] if the input was of type 1, and in matches[2] if it was of type 2. For the type-2 input, further matches of each number gets stored in matches[3] and matches[4].
You can see the demo on regex101.
Here are two solutions with slightly different semantics.
With the first, if the string is type 1 the number will be in capture group 1 (result[1]) and if it's type 2 the numbers will be in capture groups 2 and 3 (and capture group 1 will be null). The test for type 1, then, is result[1] !== null.
var a = '+/-90000';
var b = '+9000 / -80000';
var result;
var expr1 = /\+(?:\/-(\d+)|(\d+) \/ -(\d+))/;
result = a.match(expr1);
// => [ '+/-90000', '90000', null, null ]
result = b.match(expr1);
// => [ '+9000 / -80000', null, '9000', '80000' ]
With the second, if the string is type 1 the number will be in capture group 1 (and capture group 2 will be null), and if it's type 2 the numbers will be in capture groups 2 and 3. The test for type 1 is result[1] === null.
var expr2 = /\+(\d+ )?\/ ?-(\d+)/;
result = a.match(expr2);
// => [ '+/-90000', null, '90000' ]
result = b.match(expr2);
// => [ '+9000 / -80000', '9000', '80000' ]

Categories