I need a regular expression that validates a decimal number which includes +, - sign as well. For Example:
+.12
-0.13
0.+
45.-
But following are invalid Decimal numbers :
+-0.12
+99.+2
0.-12
/^[-+]?(?:0|[1-9]\d*)?\.\d*[+-]?$/gm
Flags: "g" (global) matches the entire regex as many times as it can. "m" (multiline) matches the start and end of a line with ^ and $.
^ Start of line.
[-+]? Characters "+" or "-". The question mark means the previous part can be skipped if it can't be matched.
(?:0|[1-9]\d*)? Matches either: "0", or >= 1.
\. Literal dot "."
\d* Zero or more digits (0 - 9).
[+-]? Characters "+" or "-" (optional).
$ End of line.
Related
I've read other stackoverflow posts about a simple arithmetic expression regex, but none of them is working with my issue:
I need to validate this kind of expression: "12+5.6-3.51-1.06",
I tried
const mathre = /(\d+(.)?\d*)([+-])?(\d+(.)?\d*)*/;
console.log("12+5.6-3.51-1.06".match(mathre));
but the result is '12+5', and I can't figure why ?
You only get 12.5 as a match, as there is not /g global flag, but if you would enable the global flag it will give partial matches as there are no anchors ^ and $ in the pattern validating the whole string.
The [+-] is only matched once, which should be repeated to match it multiple times.
Currently the pattern will match 1+2+3 but it will also match 1a1+2b2 as the dot is not escaped and can match any character (use \. to match it literally).
For starting with digits and optional decimal parts and repeating 1 or more times a + or -:
^\d+(?:\.\d+)?(?:[-+]\d+(?:\.\d+)?)+$
Regex demo
If the values can start with optional plus and minus and can also be decimals without leading digits:
^[+-]?\d*\.?\d+(?:[-+][+-]?\d*\.?\d+)+$
^ Start of string
[+-]? Optional + or -
\d*\.\d+ Match *+ digits with optional . and 1+ digits
(?: Non capture group
[-+] Match a + or -
[+-]?\d*\.\d+ Match an optional + or - 0+ digits and optional . and 1+ digits
)+ Close the noncapture group and repeat 1+ times to match at least a single + or -
$ End of string
Regex demo
You would try to use this solution for PCRE compatible RegExp engine:
^(?:(-?\d+(?:[\.,]{1}\d)?)[+-]?)*(?1)$
^ Start of String
(?: Non capture group ng1
(-?\d+(?:[\.,]{1}\d)?) Pattern for digit with or without start
"-" and with "." or "," in the middle, matches 1 or 1.1 or 1,1
(Matching group 1)
[+-]? Pattern for "+" or "-"
)* Says
that group ng1 might to repeat 0 or more times
(?1) Says that
it must be a digit in the end of pattern by reference to the first subpattern
$ End of string
As JS does not support recursive reference, you may use full version instead:
/^(?:(-?\d+(?:[\.,]{1}\d)?)[+-]?)*(-?\d+(?:[\.,]{1}\d)?)$/gm
I would like to allow user to type the following decimal or integer values (A)
.5
0.500
3
0
0.0
30
500000
4000.22
0.
This is the following regex that I have used:
factor: /^-?\d*[.]??\d*$/,
But the problem is that the above regex also allow the following invalid number (B)
. (comment: a single dot )
00.5 (multiple zeros before dot)
0000.5
00 (multiple zeros)
Also not allow user type negative values i.e. -3, -0.5
I am trying to modify the above regex to not allow the invalid values at (B), but allows the values at (A)
My attempt which does not work:
factor: /^-?\d*[.]+\d*$/,
Try the following regex:
^-?[1-9]*?0?(\.\d+)?$
Example Demo
you can make use of following expression which evaluates dot on the basis of digits before dot.
^-?(((?!00)\d+(?:\.{1}\d*)*)|((?!00)\d*(?:\.{1}\d+)))?$
Demo link
You could match an optional hyphen and then assert that the string does not start with 2 zeroes.
Then match optional digits, an optional dot and match 1+ digits to prevent matching an empty string.
^-?(?!00)\d*\.?\d+$
^ Start of string
-? Match optional -
(?!00) Negative lookahead, assert not 2 zeroes directly to the right
\d* Match 0+ digits
\.? Match optional .
\d+ Match 1+ digits
$ End of string
Regex demo
const regex = /^-?(?!00)\d*\.?\d+$/;
[
".5",
"0.500",
"3",
"0",
"0.0",
"30",
"500000",
"4000.22",
".",
"00.5",
"0000.5",
"00",
"-4000",
"-0",
"-00",
".",
", ",
"00.4"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));
try this regex ^-?[1-9]*\.?\d+$
the brackets say that you can have 0 or 1 digit.
I would like to capture a string that meets the criteria:
may be empty
if it is not empty it must have up to three digits (-> \d{1,3})
may be optionally followed by a uppercase letter ([A-Z]?)
may be optionally followed by a forward slash (i.e. /) (-> \/?); if it is followed by a forward slash it must have from one to three digits
(-> \d{1,3})
Here's a valid input:
35
35A
35A/44
Here's invalid input:
34/ (note the lack of a digit after '/')
I've come up with the following ^\d{0,3}[A-Z]{0,1}/?[1,3]?$ that satisfies conditions 1-3. How do I deal with 4 condition? My Regex fails at two occassions:
fails to match when there is a digit and a forward slash and a digit e.g .77A/7
matches but it shouldn't when there isa digit and a forward slash, e.g. 77/
You may use
/^(?:\d{1,3}[A-Z]?(?:\/\d{1,3})?)?$/
See the regex demo
Details
^ - start of string
(?:\d{1,3}[A-Z]?(?:\/\d{1,3})?)? - an optional non-capturing group:
\d{1,3} - one to three digits
[A-Z]? - an optional uppercase ASCII letter
(?:\/\d{1,3})? - an optional non-capturing group:
\/ - a / char
\d{1,3} - 1 to 3 digits
$ - end of string.
Visual graph (generated here):
This should work. You were matching an optional slash and then an optional digit from 1 to 3; this matches an optional combination of a slash and 1-3 of any digits. Also, your original regex could match 0 digits at the beginning; I believe that this was in error, so I fixed that.
var regex = /^(\d{1,3}[A-Z]{0,1}(\/\d{1,3})?)?$/g;
console.log("77A/7 - "+!!("77A/7").match(regex));
console.log("77/ - "+!!("77/").match(regex));
console.log("35 - "+!!("35").match(regex));
console.log("35A - "+!!("35A").match(regex));
console.log("35A/44 - "+!!("35A/44").match(regex));
console.log("35/44 - "+!!("35/44").match(regex));
console.log("34/ - "+!!("34/").match(regex));
console.log("A/3 - "+!!("A/3").match(regex));
console.log("[No string] - "+!!("").match(regex));
I have a requirement, where i have to validate a field in Excel.
Validations:
Field should start and end with [a-zA-Z0-9] but not with any special chars [-_]
It cannot contain "-" and "_" continuously more than once.
Example:
A--Badasd (Not allowed)
A__Bsdasdas (Not allowed)
A-_fdsfdsd (Not Allowed)
A_-sfsdfsdf (Not allowed)
A-B-adf (allowed)
A_b_adads (allowed)
I came up with this following regex, however, it doesn't seem to accept even the non-continuous entries of "-" and "_".
^[a-zA-z0-9]+(([\xFF01-\xFF5E]+|[\\-\\_])+)[a-zA-Z0-9]+$
[\xFF01-\xFF5E] is to not allow any double width characters, so please ignore it as it is working fine.
Any help would be greatly appreciable.
I can only suggest a lookahead based pattern (as [\xFF01-\xFF5E] matches _ and restricting it in JS regex will make the pattern more cumbersome):
/^[a-z0-9](?:(?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9])?$/i
See the regex demo.
This pattern will match strings of 1 char length, too, and will only match those strings starting and ending with an ASCII alphanumeric char and not having --, _-, -_ and __ in them.
If you want to "block" strings of length 1, i.e. set the minimum match length to 2, you should remove (?: and )? from the pattern above:
/^[a-z0-9](?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9]$/i
Details
^ - start of string
[a-z0-9] - an alphanumeric ASCII char
(?:(?!.*?[-_]{2})[\xFF01-\xFF5E_-]*[a-z0-9])? - an optional (1 or 0 occurrences) sequence of:
(?!.*?[-_]{2}) - a lookahead check that will fail the match if there are 2 consecutive - or _ anywhere after any 0+ chars other than line break chars
[\xFF01-\xFF5E-]* - any char in the \xFF01-\xFF5E range or/and -
[a-z0-9] - an alphanumeric ASCII char
$ - end of string.
This is a solution for validating an integer. Can someone please explain the logic of Karim's answer.
This works perfectly, but i am not able to understand how.
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
The regex: /^\d+$/
^ // beginning of the string
\d // numeric char [0-9]
+ // 1 or more from the last
$ // ends of the string
when they are all combined:
From the beginning of the string to the end there are one or more numbers char[0-9] and number only.
Check out a Regular Expression reference: http://www.javascriptkit.com/javatutors/redev2.shtml
/^\d+$/
^ : Start of string
\d : A number [0-9]
+ : 1 or more of the previous
$ : End of string
This regex may be better /^[1-9]+\d*$/
^ // beginning of the string
[1-9] // numeric char [1-9]
+ // 1 or more occurrence of the prior
\d // numeric char [0-9]
* // 0 or more occurrences of the prior
$ // end of the string
Will also test against non-negative integers that are pre-padded with zeroes
What is a Nonnegative Whole Number?
A Nonnegative whole number is an "integer that is either 0 or positive."
Source: http://mathworld.wolfram.com/NonnegativeInteger.html
In other words, you are looking to validate a nonnegative integer.
The answers above are insufficient because they do not include integers such as -0 and -0000, which, technically, after parsing, become nonnegative integers. The other answers also do not validate integers with + in front.
You can use the following regex for validation:
/^(\+?\d+|-?0+)$/
Try it Online!
Explanation:
^ # Beginning of String
( # Capturing Group
\+? # Optional '+' Sign
\d+ # One or More Digits (0 - 9)
| # OR
-? # Optional '-' Sign
0+ # One or More 0 Digits
) # End Capturing Group
$ # End of String
The following test cases return true: -0, -0000, 0, 00000, +0, +0000, 1, 12345, +1, +1234.
The following test cases return false: -12.3, 123.4, -1234, -1.
Note: This regex does not work for integer strings written in scientific notation.