I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits.
Valid Input
1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11
Invalid Input
a
a.
1.a
1.111
1.1111
string allows any number of digit characters, but only allows 1 decimal/period
if a period/decimal exists: only allow 2 digit characters after the decimal
Here is the regex I came up with
\d*\.?([\d]){0,2}
I am having trouble testing it to ensure it works. I found a couple ways of testing it. Using the test method which I just used w3schools setup here. The other way was with some javascript regular expression tester like regexr and regex101. For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.
Question: What regex would do what I want it to do?
You need to make sure that you check the complete string (from the first char to the last char) using ^...$
The first digit should appear at least 1 time (so you want to use + and not *).
Check this example:
r = /^\d+\.?\d{0,2}$/
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
update
Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this:
r = /^\d+(\.\d\d{0,1})?$/
console.log('1.'.match(r))
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
Don't forget closing and opening in Regex, many new Regex for get it and they end up unwanted result, everything should between ^ and $, ^ is starting point of the word(digit) boundary and $ is ending point...something like below should help you, try:
'use strict';
var decimal = /^\d+(\.\d\d{0,2})$/, num = 111111111.11;
console.log(decimal.test(num));
Hope this helps...
Related
Hello to the community I have a query, I need a validation Regex, for amounts without decimals, that consider valid the following structure.
99,999,999
If I add a value:
12345678 -> Ok
12,345,678 -> Ok
123,456,789 -> Failed
123,45,6,78 -> Failed
12,345,678.50 -> Failed
12,456,7ab -> Failed
I have only been able to validate the size of 8 numerical characters:
var regex8 = /^-?([0-9]{1,8})?$/;
I wait for your comments.
Thank you.
With a bit of work you can craft a pattern to do this:
https://regex101.com/r/DKpSUR/1
/^-?([0-9]{1,2},?)?([0-9]{3},?){1,2}$/
This regex should supply you with what you want or point you in a direction:
-?([0-9]{1,2},)?([0-9]{3},)?[0-9]{3}
This will match an optional leading sign [-+]?
followed by either
a string of one or more digits \d+ or
a 1-3 digit string \d{1,3} followed by one more more groups of comma-3-digits ,\d{3}
Putting it all together:
/^[-+]?((\d+)|(\d{1,3}(,\d{3})+))$/
I have grouped them with parentheses () to make it clear, but be aware this creates capturing groups.
var rgx = /^[-+]?((\d+)|(\d{1,3}(,\d{3})+))$/
var matched = "+813,823".match(rgx); // ==> ["+813,823", "813,823", undefined, "813,823", ",823"]
You would want matched[0] to get the whole match.
Note: Not a repeat of any question I could find.
I need a regex to allow these conditions:
1234.789 // Invalid (as it contains decimal)
+1234.789 // Invalid (as it contains decimal again)
12345678+ // Invalid (as it contains + in the end)
+1234324 // valid
I have tried a lot of options and I could write a regex which allows only numbers and + at the beginning alone but couldn't combine both.
/[^\+]+$/
+ allowed only at the end
/^[0-9]*[0-9]*$/
Only numbers, no +/- symbols.
I need help in getting both combined.
Use Character Classes and Anchoring
In JavaScript, you don't have \A or \z atoms, so you have to anchor with either ^, $, or \b as needed. For example, this regex will work with your corpus:
/^[+-]?\d+$/
If you have trailing spaces, or other irregularities in your real input, then you'll have to adjust the regular expression accordingly. However, this should get you started.
Sample Code
You can test it yourself on your sample input. For example:
[
'1234.789',
'+1234.789',
'12345678+',
'+1234324',
'-1234324',
'12345789'
].forEach(function (str) {
var result = str.match(/^[+-]?\d+$/);
if (result) {
console.log(' valid: ' + result);
} else {
console.log('invalid: ' + str);
};
});
Output
The code above yields the expected results:
invalid: 1234.789
invalid: +1234.789
invalid: 12345678+
valid: +1234324
valid: -1234324
valid: 12345789
You need to specify + or - as an option 0 or 1 times ([+-]{0,1}) then digits one or more times (\d+). Put them together, and the regex would look like this:
[+-]{0,1}\d+
I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript.
Here's the regex pattern I am using:
var numberPattern = /^9[0-9]{9}/;
Here's the pattern matching phase:
var numberstring = JSON.stringify(data[i].text);
if(numberPattern.test(data[i].text.toString()) == true){
var obj={
tweet : {
status : data[i].text
},
phone : numberstring.match(numberPattern)
}
//console.log(numberstring.match(numberPattern));
stringarray.push(obj);
The problem is it is working for few numbers and not all. Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. I'm a beginner in regex, so help is needed. Thanks.
Example:
#Chennai O-ve blood for #arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via #arun_scribbles
Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/.
To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\+?(9|8)[0-9]{9}/.
To allow any character except "0", replace the (9|8) with a construct to accept only 1-9: /^\+?[1-9][0-9]{9}/.
And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. If you're looking for content in the middle of the line, you'll need to drop the caret: /\+?[1-9][0-9]{9}/.
var numberPattern = /([+]91)?9[0-9]{9}\b/;
Try this regex pattern: [\+]?[0-9]{1,4}[\s]?[0-9]{10}
It accepts any country code with +, a space, and then 10 digit number.
I am new to regular expressions and i would like to validate user input with javascript.
The user input is a currency, but i want it without the thousands commata.
Valid
"12.34"
"12,34"
"1234,5"
"123"
"123,00"
"12000"
Invalid
"12a34"
"abc"
"12.000,00"
"12,000.00"
I tried the following regex-pattern, but it doesnt work for me. it validates for example "12a34" and i dont know why.
/\d+([\.|\,]\d+)?/
What would be the correct regex-pattern ? Could you explain this step by step ?
Thanks !
Do not escape the . while in a character group. Try with following regex:
/^\d+([.,]\d{1,2})?$/
^ = start of string
$ = end of string
()? = an optional capturegroup ( e.g. to validate "123")
{x,y} = The symbol may occur minimum x and maximum y times
RegExp: /^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$/g
pattern: ^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$
flags: g
3 capturing groups:
group 1: (0|[1-9]\d{0,2}(,?\d{3})?)
group 2: (,?\d{3})
group 3: (\.\d\d?)
Regex Test
function validateDecimal(number,maxDigits)
{
eval("var stringvar=/^[-+]?([0-9]*\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");
return stringvar.test(number);
}
I wrote above function to validate decimal numbers. The variable 'maxDigits' uses to specify the number of digits in fractional part and 'number' as the value to be validated. But it returned 'true' when I tried with a numeric value followed by a character for eg: 24y. Can anyone help me to figure out my mistake.
Without going into the regex, I think the problem in your code is that you should escape the special character twice. Since you're putting it all inside a string, a single backslash is escaped by the string parsing.
I think this should work:
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");
This regular expression would validate a number with maxDigits of decimals:
^[-+]?[0-9]*.[0-9]{10}$. This will validate it to 10 decimal places.
Implementing that into JavaScript would look like:
eval("var stringvar=^[-+]?[0-9]*.[0-9]{" + maxDigits + "}$");, or thereabouts.
I have just tried this one and it worked for me: ^[+-]?[0-9]*(\.[0-9]{0,5})?$.
In my case I made a minor modification, you seem to be matching either a decimal number or else a whole number. In my case, I modified the regular expression to take a whole number with an optional decimal section.
As is, the regular expression will match values like: .222, 23.22222 but not 4d.22222, 33.333333, etc.
var n1 = "4.33254";
var n2 = "4d.55";
eval("var stringvar=/^[+-]?[0-9]*(\\.[0-9]{0,5})?$/");
alert(stringvar.test(n1));
alert(stringvar.test(n2));
Yielded: true and false respectively.