How to limit total number of digits in a decimal number - javascript

I have this regex which validates if a string is a decimal number.
Also this checks if it has at most 9 decimals after ".".
^[-]?[0-9]+([\.][0-9]{0,9})?$
I need to add another check, which limits the total number of digits.
Mention: I need the total number of digits to be less then 38, including the decimal after the point, thus I cannot add the range just to decimals before the point.
valid ex:
-12345678901234567890123456789.123456789
123456789012345678901234567890.1
-1.123456789

Use a negative lookahead:
^(?=(?:\D*\d){n}\D*$)[-]?[0-9]+(?:\.[0-9]{0,9})?$
^^^^^^^^^^^^^^^^^^^^
Where n is the limit argument for the amount of digits in the input string.
Example:
^(?=(?:\D*\d){7}\D*$)-?[0-9]+(?:\.[0-9]{0,9})?$
will match 1234.567, but will not match 1234.56 and 1234.5678.
See the regex demo
Now,
I need the total number of digits to be less then 38
Just use a negative lookahead:
^(?!(?:\D*\d){38})-?[0-9]+(?:\.[0-9]{0,9})?$
^^^^^^^^^^^^^^^^^
This (?!(?:\D*\d){38}) lookahead will fail the match if there are 38 (not obligatorily consecutive due to \D*) digits in the string.
Pattern explanation:
^ - start of string
(?!(?:\D*\d){38}) - the negative lookahead that will try to match 0+ non-digits (\D*) followed with a digit exactly 38 times and if it matches that text, no match will be returned
-? - an optional (1 or 0) hyphen (no need to place it into a character class as it is not a special regex metacharacter here)
[0-9]+ - 1+ digits (use \d instead to make it shorter)
(?:\.[0-9]{0,9})? - an optional (1 or 0 occurrences) sequence of:
\. - a literal dot
[0-9]{0,9} - 0 to 9 digits (again, \d{0,9} is shorter)
$ - end of string
And if you need to only check the integer part to have less than 38 digits, use
^(?!(?:[^\d.]*\d){38})[-]?[0-9]+(?:\.[0-9]{0,9})?$
See this regex demo

You can use regex with positive look ahead assertion /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/
$('input').on('input', function() {
$(this).css('color', /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/.test(this.value) ? 'green' : 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input>
Regex explanation

Related

Javascript Regular Expresion [duplicate]

I'm trying to write a RegExp to match only 8 digits, with one optional comma maybe hidden in-between the digits.
All of these should match:
12345678
12,45678
123456,8
Right now I have:
^[0-9,]{8}
but of course that erroneously matches 012,,,67
Example:
https://regex101.com/r/dX9aS9/1
I know optionals exist but don't understand how to keep the 8 digit length applying to the comma while also keeping the comma limited to 1.
Any tips would be appreciated, thanks!
To match 8 char string that can only contain digits and an optional comma in-between, you may use
^(?=.{8}$)\d+,?\d+$
See the regex demo
The lookahead will require the string to contain 8 chars. ,? will make matching a comma optional, and the + after \d will require at least 1 digit before and after an optional comma.
If you need to match a string that has 8 digits and an optional comma, you can use
^(?:(?=.{9}$)\d+,\d+|\d{8})$
See the regex demo
Actually, the string will have 9 characters in the string (if it has a comma), or just 8 - if there are only digits.
Explanation:
^ - start of string
(?:(?=.{9}$)\d+,\d+|\d{8}) - 2 alternatives:
(?=.{9}$)\d+,\d+ - 1+ digits followed with 1 comma followed with 1+ digits, and the whole string matched should be 9 char long (8 digits and 1 comma)
| - or
\d{8} - 8 digits
$ - end of string
See the Java code demo (note that with String#matches(), the ^ and $ anchors at the start and end of the pattern are redundant and can be omitted since the pattern is anchored by default when used with this method):
List<String> strs = Arrays.asList("0123,,678", "0123456", // bad
"01234,567", "01234567" // good
);
for (String str : strs)
System.out.println(str.matches("(?:(?=.{9}$)\\d+,\\d+|\\d{8})"));
NOTE FOR LEADING/TRAILING COMMAS:
You just need to replace + (match 1 or more occurrences) quantifiers to * (match 0 or more occurrences) in the first alternative branch to allow leading/trailing commas:
^(?:(?=.{9}$)\d*,\d*|\d{8})$
See this regex demo
You can use following regex if you want to let trailing comma:
^((\d,?){8})$
Demo
Otherwise use following one:
^((\d,?){8})(?<!,)$
Demo
(?<!,) is a negative-lookbehind.
/^(?!\d{0,6},\d{0,6},\d{0,6})(?=\d[\d,]{6}\d).{8}$/
I guess this cooperation of positive and negative look-ahead does just what's asked. If you remove the start and end delimiters and set the g flag then it will try to match the pattern along decimal strings longer than 8 characters as well.
Please try http://regexr.com/3d63m
Explanation: The negative look ahead (?!\d{0,6},\d{0,6},\d{0,6}) tries not to find any commas side by side if they have 6 or less decimal characters in between while the positive look ahead (?=\d[\d,]{6}\d) tries to find 6 decimal or comma characters in between two decimal characters. And the last .{8} selects 8 characters.

Generic JavaScript regex validating a positive number with or without commas as thousand separators and an optional fractional part

I have following regex to validate numbers in input
var reg = /^\d+$/;
Now i want to allow ,(commas) and .(period) in number field as following will some one help me writing regex to allow following number format ?
10000000
10,000,000
10000000.00
You may use
/^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?$/
See the regex demo
If you only need to allow 2 digits after the decimal separator, replace (?:\.\d+)? with (?:\.\d{1,2})?.
Details:
^ - start of string
(?:\d{1,3}(?:,\d{3})*|\d+) - 2 alternatives:
\d{1,3}(?:,\d{3})+ - 1 to 3 digits and one or more sequences of a comma and 3 digits
\d+ - 1 or more digits
(?:\.\d+)? - an optional sequence of:
\. - a dot
\d+ - 1 or more digits
$
You could use
^((\d{1,2}(,\d{3})+)|(\d+)(\.\d{2})?)$
see Regex101
or
^((\d{1,2}(,\d{3})+)|(\d+))(\.\d{2})?$
if you want 10,000,000.00 to get matched to.

Regex for phone numbers that check if numbers are not the same and last 7 digits are not same

I am trying to create a regex which matches 7-15 digit number, the number cannot contain all the same digits and Last 7 digits cannot be the same. I have made two regex expressions for number that all numbers cannot be same. The regex which I have made is:
/^(?!(.)\1+$)^(|[0-9]{7,15})$/.
And for Last seven digits cannot be same,the regex which i have made is:
/^(?!.*(\d)\1{6}\b)^[0-9]{0,15}$/.
But the problem is I am not able to make the regex which full fills both the conditions i.e. all the numbers cannot contain all the same digits and Last 7 digits cannot be the same.
Please suggest how this can be done.
It seems you can use alternation operator inside the negative lookahead to check for 2 conditions:
^(?!(\d)\1+$|\d*(\d)\2{6}$)(?:\d{7,15})?$
See the regex demo.
Details:
^ - start of string
(?!(\d)\1+$|\d*(\d)\2{6}$) - the negative lookahead failing the match if all digits are the same from start to end ((\d)\1+$ where (\d) captures a digit into Group 1 and then \1+ matches one or more values captured in Group 1 followed with end of string check with $), or if only the last 7 are the same (see \d*(\d)\2{6}$ where \d* matches 0+ digits, (\d) captures a digit into Group 2 and then \2{6} matches 6 values captured in Group 2 followed with end of string check with $)
(?:\d{7,15})? - an optional group matching 7 to 15 digits (or an empty string, as it's optional)
$ - end of string.

Regex Min Max for Expression that Allows Spaces

I am using this pattern:
^\w+( \w+)*$
to validate that a string is alphanumeric and may contain spaces. I can't figure out how to set a min and max though. I'd like something like this:
^(\w+( \w+)*){1, 50}$
but it's not working. What is the correct syntax?
EDIT: Sample input:
3this String is fine12
If the length of the entire string is greater than 50 though, it should not match.
If you want to limit the input string length you can use a restrictive positive lookahead at the start:
/^(?=.{1,50}$)\w+(?: \w+)*$/
The input string length can range from 1 to 50 characters.
See regex demo
Explanation:
^ - start of string
(?=.{1,50}$) - the positive lookahead that requires the string to have at least 1 character and up to 50 (note the $ is very important here)
\w+ - 1 or more word characters
(?: \w+)* - zero or more sequences of a space followed by 1 or more word characters
$ - end of string

Regular Expression not working as expected in javascript

I have following regular expression: ^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)
It should not allow 4 digit number such as 4444. The expression is working fine if I try here, but in javascript, the code is not working as expected. It is allowing 4 digit numbers. All other validations work fine.
Here is my code:
http://jsfiddle.net/PAscG/
reg0str = "^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)";
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;
UPDATE TO EXPLAIN Functionality:
I want to allow only 3 digits. So either I can allow only 1 digit after decimal and 2 before decimal or I can allow max of 3 digits before decimal and nothing after decimal.
So my first part:
[0-9]{0,3}$ I assume this should allow a max of 3 digits and only numbers.
Next part: [0-9]{0,2}\.?[0-9]{0,1}$ should allow max of 2 digits before decimal and a max of 1 digit after decimal.
Following OP's clarification
The regexp is
/^-?(\d{0,3}\.?|\d{0,2)\.\d)$/
^ start of string
-? optional minus sign (use [-+]? if you accept a plus sign)
( start of OR group
\d{0,3} 0 1, 2 or 3 digits
\.? optional decimal point
| OR
\d{0,2} 0 1, or 2 digits
\. decimal point
\d final decimal
) end of OR grouping
$ end of string
Try this:
var reg0str = "^\-?[0-9]{0,2}[\.]?[0-9]?$";
I'm not sure why, but the period seems to be being treated as the wildcard character if not encapsulated within a class.
Here's the updated jsfiddle
"…\.…" is a string literal - the backslash escapes the dot to a dot and the regex dot matches a digit. You would need to escape the backslash to pass a string with a backslash in the RegExp constructor:
new RegExp("^-?([0-9]{0,3}$|[0-9]{0,2}\\.?[0-9]{0,1}$)")
or you use a regex literal (simplified, but still matching the same):
/^-?\d{0,2}\.?\d?$/

Categories

Resources