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.
Related
I need to match a pattern for validation . I want to match a decimal number where numeric part can have upto 14 digits including + or - without 0 and after decimal has upto 4 digits. Valid patterns are :
+1.23
9857.6543
-745290.0
Invalid patterns are:
0
0.00
1.23456
I have tried ^[0-9]{0,14}\.[0-9]{0,4}$.
I am not getting how to match for +,- and 0 condition
Short answer: ^[+-]?[1-9][0-9]{0,13}\.[0-9]{1,4}$
^ - start of string
[+-]? optionally, one between + and -
[1-9][0-9]{0,13} - a 14 digit number that doesn't start with 0
\. - decimal separator, has to be escaped or it will mean "any one character"
[0-9]{1,4} - up to 4 decimal digits
$ - end of string
This might work ^(\+|-)?(([1-9]|0(?=0*[1-9]))[0-9]{0,13}(\.[0-9]{1,4})?|0{1,14}\.(?=0*[1-9])[0-9]{1,4})$
^(\+|-)? - starts with +/-
(
([1-9]|0(?=0*[1-9]))[0-9]{0,13}(\.[0-9]{1,4})? - absolute value >= 1
| - or
0{1,14}\.(?=0*[1-9])[0-9]{1,4} - 0.**** with at least 1 non-zero digit
)
$ - end
const testcases = [
'+1.23',
'9857.6543',
'-745290.0',
'1.0',
'1.00',
'12',
'0.01',
'+001.01',
'0',
'0.00',
'1.23456',
'0.0',
'12.'];
const regex = /^(\+|-)?(([1-9]|0(?=0*[1-9]))[0-9]{0,13}(\.[0-9]{1,4})?|0{1,14}\.(?=0*[1-9])[0-9]{1,4})$/;
testcases.forEach(n => console.log(`${n}\t - ${regex.test(n)}`));
The pattern:
^[+-]?[^\D0]\d{0,13}\.\d{1,4}(?!\d)
matches the first 3 but not the second 3. [^\D0] is, if I'm not mistaken, strictly the same as [123456789], but slightly more compact.
You can assert that the string does not start with 1 or more zeroes, followed by an optional dot and optional zeroes.
Then match 1-14 digits and optionally a dot and 1-4 digits, which would also allow for 00001 for example
^(?!0+\.?0*$)[+-]?\d{1,14}(?:\.\d{1,4})?$
The pattern matches:
^ Start of string
(?!0+\.?0*$) Negative lookahead, assert not 1+ zeroes, optional dot and optional zeroes
[+-]? Optionally match + or -
\d{1,14} Match 1-14 digits
(?:\.\d{1,4})? Optionally match . and 1-4 digits
$ End of string
Regex demo
How about this?
^(?!0\.?0*$)[\+\-]?[0-9]{1,14}\.?[0-9]{0,4}$
Note: this does not match decimals without a leading 0 like .123 and does not match numbers with spaces in between the + or -. Though, these could be added to the pattern.
Requiring a non-zero digit before a . eliminates fractions of whole numbers, like 0.123.
Also, if you don't want integers and only want decimals, you will need to modify to make the . required:
^(?!0\.?0*$)[\+\-]?[0-9]{1,14}\.[0-9]{0,4}$
examples where the regex should return true: 1&&2, 1||2, 1&&2||3, 1
examples where the regex should return false: 1||, 1&&, &&2
My regex is:
[0-9]+([\\|\\|\\&&][0-9])*
but it returns true if the input is 1&&&2.
Where is my mistake?
Note that [\|\|\&&] matches a single | or & char, not || or && sequences of chars. Also, the [0-9] without a quantifier matches only one digit. Without anchors, you may match a string partially inside a longer string.
You may use
^[0-9]+(?:(?:\|\||&&)[0-9]+)*$
Actually, to match anywhere inside a string, keep on using the pattern without anchors:
[0-9]+(?:(?:\|\||&&)[0-9]+)*
See the regex demo
Details
^ - start of string
[0-9]+ - 1+ digits
(?:(?:\|\||&&)[0-9])* - 0 or more repetitions of
(?:\|\||&&) - || or && sequence of characters
[0-9]+ - 1+ digits
$ - end of string.
JS demo:
const reg = /^[0-9]+(?:(?:\|\||&&)[0-9]+)*$/;
console.log( reg.test('1||2') ); // => true
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.
I need JavaScript regular expression for business name with following conditions:
Numbers, spaces and the following characters are allowed:
~ ` ? ! ^ * ¨ ; # = $ % { } [ ] | /. < > # “ - ‘
Should be at least 2 characters one of which must be alpha or numeric character
No preceding or trailing spaces
examples: Test1, Ta, A1, M's, 1's, s!, 1!
I tried following (for time being I used only 3 special characters for testing purpose):
^(?=(?:[^\A-Za-z0-9]*[\A-Za-z0-9]){2})[~,?,!]*\S+(?: \S+){0,}$
But it doesn't validate s! or 1!.
You can use the following to validate:
^(?!\s)(?!.*\s$)(?=.*[a-zA-Z0-9])[a-zA-Z0-9 '~?!]{2,}$
And add all the characters tht you want to allow in [a-zA-Z0-9 '~?!]
See DEMO
Explanation:
^ start of the string
(?!\s) lookahead assertion for don't start with space
(?!.*\s$) lookahead assertion for don't end with space
(?=.*[a-zA-Z0-9]) lookahead assertion for atleast one alpha or numeric character
[a-zA-Z0-9 '~?!] characters we want to match (customize as required)
{2,} match minimum 2 and maximum any number of characters from the previously defined class
$ end of the string
i'd like to make a javascript validation that will accept all numeric and decimal point format.
For example :
1,000,000.00 is OK
1.000.000,00 is OK
1.000,000.00 is not OK
1.000,000,00 is not OK
1,000.000,00 is not OK
1,000.000.00 is not OK
Based on what i got here is :
/^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?$/ is only valid for 1,000,000.00 not for 1.000.000,00
How can i validate both format ?
Updated :
What if the thousand points are not compulsory such as :
1000000.00 is OK or
1000000,00 is OK
Assuming that the decimal part and thousands separators are mandatory, not optional, and that 0 is not an allowed value (as suggested by your examples and your regex):
^[1-9]\d{0,2}(?:(?:,\d{3})*\.\d{2}|(?:\.\d{3})*,\d{2})$
As a verbose regex:
^ # Start of string
[1-9]\d{0,2} # 1-3 digits, no leading zero
(?: # Match either...
(?:,\d{3})* # comma-separated triple digits
\.\d{2} # plus dot-separated decimals
| # or...
(?:\.\d{3})* # dot-separated triple digits
,\d{2} # plus comma-separated decimals
) # End of alternation
$ # End of string
Here is the regex that you want..
^(([1-9]\d{0,2}(((\.\d{3})*(,\d{2})?)|((,\d{3})*(\.\d{2})?)))|(0(\.|,)\d{1,2})|([1-9]\d+((\.|,)\d{1,2})?))$
This is the link that proves that it can handles all cases
http://regexr.com?2tves
The best way to look at a regular expression this big is to blow it up to
a very large font and split it on the alternatives (|)
var s='1,000,000.00';// tests
var result= /(^\d+([,.]\d+)?$)/.test(s) || // no thousand separator
/((^\d{1,3}(,\d{3})+(\.\d+)?)$)/.test(s) || // comma thousand separator
/((^\d{1,3}(\.\d{3})+(,\d+)?)$)/.test(s); // dot thousand separator
alert(result)
Put together its a brute-
function validDelimNum2(s){
var rx=/(^\d+([,.]\d+)?$)|((^\d{1,3}(,\d{3})+(\.\d+)?)$)|((^\d{1,3}(\.\d{3})+(,\d+)?)$)/;
return rx.test(s);
}
//tests
var N= [
'10000000',
'1,000,000.00',
'1.000.000,00',
'1000000.00',
'1000000,00',
'1.00.00',
'1,00,00',
'1.000,00',
'1000,000.00'
]
var A= [];
for(var i= 0, L= N.length; i<L; i++){
A.push(N[i]+'='+validDelimNum2(N[i]));
}
A.join('\n')
/* returned values
10000000=true
1,000,000.00=true
1.000.000,00=true
1000000.00=true
1000000,00=true
1.00.00=false
1,00,00=false
1.000,00=true
1000,000.00=false
*/
The simplest (though not most elegant by far) method would be to write analogous RE for another case and join them with 'OR', like this:
/^(([1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?)|([1-9][0-9]{0,2}(\.[0-9]{3})*(,[0-9]{2})?))$/
UPDATE
A little cleaned up version
/^[1-9]\d{0,2}(((,\d{3})*(\.\d{2})?)|((\.\d{3})*(,\d{2})?))$/
You can replace the , and \. with [,.] to accept either in either location. It would also make 1,000.000.00 OK though.
Its harder to make the regexp behave like that in JavaScript because you can't use lookbehinds
/^(0|0[.,]\d{2}|[1-9]\d{0,2}((,(\d{3}))*(\.\d{2})?|(\.(\d{3}))*(,\d{2})?))$/
/^ #anchor to the first char of string
( #start group
0 # 0
| # or
0[.,] # 0 or 0 followed by a . or ,
\d{2} # 2 digits
| # or
[1-9] #match 1-9
\d{0,2} #0-2 additional digits
( #start group
(,(\d{3}))* # match , and 3 digits zero or more times
(\.\d{2})? # match . and 2 digits zero or one
| # or
(\.(\d{3})* # match . and 3 digits zero or more times
(,\d{2})? # match , and 2 digits zero or one time
) #end group
) #end group
$/ #anchor to end of string
http://jsfiddle.net/AC3Bm/