RegEx for currency (JavaScript) - javascript

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

Related

Validation Regex for quantities with centesimal and without centesimal ...?

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.

Test if a sentence is matching a text declaration using regex

I want to test if a sentence like type var1,var2,var3 is matching a text declaration or not.
So, I used the following code :
var text = "int a1,a2,a3",
reg = /int ((([a-z_A-Z]+[0-9]*),)+)$/g;
if (reg.test(text)) console.log(true);
else console.log(false)
The problem is that this regular expression returns false on text that is supposed to be true.
Could someone help me find a good regular expression matching expressions as in the example above?
You have a couple of mistekes.
As you wrote, the last coma is required at the end of the line.
I suppose you also want to match int abc123 as correct string, so you need to include letter to other characters
Avoid using capturing groups for just testing strings.
const str = 'int a1,a2,a3';
const regex = /int (?:[a-zA-Z_](?:[a-zA-Z0-9_])*(?:\,|$))+/g
console.log(regex.test(str));
You will need to add ? after the comma ,.
This token ? matches between zero and one.
Notice that the last number in your text a3 does not have , afterward.
int ((([a-z_A-Z]+[0-9]*),?)+)$

Regex to match if string contains integer/decimal with digits

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...

Regex match with 3 condition?

I will creating math program .If i wish to solve i need separate to the equation using with regex.
For example:
`10x-10y2+100x-100k=100`
the format will separate with regex output: "10x" ,"100x" ,"100k" ,"10y2","100"
I have already code for that with separate match function
There are:
for num[a-z]num : ` /([\-+])?\s*(\d+)?([a-z]?(\d+))/g`
for num[a-z] : ` /([\-+])?\s*(\d+)?([a-z]?(\d+))/g`
fon num : `/\b[+-]?[\d]+\b/g`
I need all this three match function within one regex match function.some one help to combine the code with single regex expression
Note :i need match function only not a split beacause i apply that regex expression into parser
Thank You.
Split on symbols:
"10x-10y2+100x-100k=100".split(/[-+=]/);
Output:
["10x", "10y2", "100x", "100k", "100"]
If you need to use match() method I suggest same approach:
"10x-10y2+100x-100k=100".match(/[^-+=]+/g);
Output is the same.
/(?:0|[1-9]\d*)?(?:[a-z]+)?(?:\^(?:0|[1-9]\d*))?/g
// finds:
// vvv vvvvv vvvv vvvv vvvvv vv vvv v vvv
10x-10y^2+100x-100k=100^4+xy+100+100y2+0-1^0
// doesn't find: ^^^^^
(?:0|[1-9]\d*)? 0, OR 1-9 then zero or more numbers. Optional.
(?:[a-z]+)? Optional one or more lowercase letters.
(?:\^[1-9]\d*)? Optional power.
\^ Literal text.
(?:0|[1-9]\d*) Zero, OR 1-9 then zero or more numbers.
If I've missed anything let me know and I'll incorporate it.
Just try with following regex:
/(\d+[a-z]?\d*)/g
example
Try this:
s.match(/\d+([A-Za-z]\d*)?/g)

Regexp for all numbers or just one specific symbol

I need to verify if string consists of numbers only or just with one '*' symbol.
Correct:
*
123
5
Incorrect:
**
23*
*2
abc
I've tried new RegExp('[\*?|\d*]') but it doesn't allow numbers and allow multiple *
what about that : ^(?:\*|\d+)$
?: is for non capturing group.
Try this regex: "^\d*$"
^: start of the string, $: end of the string
There You go :
(^\*{1}$|^\d+$)
tested in notepad++
The solution using RegExp.test and String.match functions:
var checkString = function(str){
var ast_matches = str.match(/[*]/g); // asterisk symbol matches
return /^[*\d]+$/.test(str) && (!ast_matches || ast_matches.length === 1);
};
console.log(checkString("1235")); // true
console.log(checkString("*1235")); // true
console.log(checkString("**23*2abc")); // false
I would use this regex: ^(\*|[0-9]*)$:
^...$ for matching the whole line
(|) for defining two alternatives
\* alternative 1: one star only
[0-9]* alternative 2: numbers only
You can play with the regex here.
You can create the regex object like this: new RegExp(/^[0-9]*\*?[0-9]*$/); I.e. without the apostrophes. You can play with that here.

Categories

Resources