Regular Expression not working as expected in javascript - 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?$/

Related

Limit 10 characters is numbers and only 1 dot

I'm having a regex problem when input
That's the requirement: limit 10 characters (numbers) including dots, and only 1 dot is allowed
My current code is only 10 characters before and after the dot.
^[0-9]{1,10}\.?[0-9]{0,10}$
thank for support.
You could assert 10 chars in the string being either . or a digit.
Then you can match optional digits, and optionally match a dot and again optional digits:
^(?=[.\d]{10}$)\d*(?:\.\d*)?$
The pattern matches:
^ Start of string
(?=[.\d]{10}$) Positive lookahead, assert 10 chars . or digit till the end of string
\d* Match optional digits
(?:\.\d*)? Optionally match a `. and optional digits
$ End of string
See a regex demo.
If the pattern should not end on a dot:
^(?=[.\d]{10}$)\d*(?:\.\d+)?$
Regex demo
The decimal point throws a wrench into most single pattern approaches. I would probably use an alternation here:
^(?:\d{1,10}|(?=\d*\.)(?!\d*\.\d*\.)[0-9.]{2,11})$
This pattern says to match:
^ from the start of the number
(?:
\d{1,10} a pure 1 to 10 digit integer
| OR
(?=\d*\.) assert that one dot is present
(?!\d*\.\d*\.) assert that ONLY one dot is present
[0-9.]{2,11} match a 1 to 10 digit float
)
$ end of the number
You can use a lookahead to achieve your goals.
First, looking at your regex, you've used [0-9] to represent all digit characters. We can shorten this to \d, which means the same thing.
Then, we can focus on the requirement that there be only one dot. We can test for this with the following pattern:
^\d*\.?\d*$
\d* means any number of digit characters
\.? matches one literal dot, optionally
\d* matches any number of digit characters after the dot
$ anchors this to the end of the string, so the match can't just end before the second dot, it actually has to fail if there's a second dot
Now, we don't actually want to consume all the characters involved in this match, because then we wouldn't be able to ensure that there are <=10 characters. Here's where the lookahead comes in: We can use the lookahead to ensure that our pattern above matches, but not actually perform the match. This way we verify that there is only one dot, but we haven't actually consumed any of the input characters yet. A lookahead would look like this:
^(?=\d*\.?\d*$)
Next, we can ensure that there are aren't more than 10 characters total. Since we already made sure there are only dots and digits with the above pattern, we can just match up to 10 of any characters for simplicity, like so:
^.{1,10}$
Putting these two patterns together, we get this:
^(?=\d*\.?\d*$).{1,10}$
This will only match number inputs which have 10 or fewer characters and have no more than one dot.
If you would like to ensure that, when there is a dot, there is also a digit accompanying it, we can achieve this by adding another lookahead. The only case that meets this condition is when the input string is just a dot (.), so we can just explicitly rule this case out with a negative lookahead like so:
(?!\.$)
Adding this back in to our main expression, we get:
^(?=\d*\.?\d*$)(?!\.$).{1,10}$

Regex for allow negative values and decimal values in javascript

I want to allow only the four decimal values followed by numbers and can allow negative numbers.
$(document).on("keyup", "input[name='measuredqty']", function(){
if (/\D/g.test(this.value)){
this.value = this.value.match(/^-\d+\.?\d{0,4}/);
}
});
This regular expression should do what you want:
/^-?\d+(\.\d{0,4})?$/
^ forces starting at the beginning of the string
-? allows an optional minus
\d+ allows one or more digits
(\.\d{0,4})? says the decimal part is optional, with up to 4 digits
$ forces finishing at the end of the string

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.

How to limit total number of digits in a decimal number

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

Categories

Resources