Javascript Regular expression for currency amount with spaces - javascript

I have this regular expression
/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+, <,>,\),\*,\-,%]?$/
It matches this very well $55.5, but in few of my test data I have some values like $ 55.5 (I mean, it has a space after $ sign).
The answers on this link are not working for me.
Currency / Percent Regular Expression
So, how can I change it to accept the spaces as well?

Try following RegEx:
/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+, <,>,\),\*,\-,%]?$/
Let me know if it worked!
Demo Here

TLDR:
/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+, <,>,\),\*,\-,%]?$/
The science bit
Ok, I'm guessing that you didn't construct the original regular expression, so here are the pieces of it, with the addition marked:
^ # match from the beginning of the string
[',",\+,<,>,\(,\*,\-,%]? # optionally one of these symbols
( # start a group
[£,$,€]? # optionally one of these symbols
\s* # <--- NEW ADDITION: optionally one or more whitespace
\d+ # then one or more decimal digits
( # start group
[\,,\.] # comma or a dot
\d+ # then one or more decimal digits
)? # group optional (comma/dot and digits or neither)
[£,$,€]? # optionally one of these symbols
\s* # optionally whitespace
[\-,\/,\,,\.,\+]? # optionally one of these symbols
[\/]? # optionally a /
\s* # optionally whitespace
)+ # this whole group one or more times
[',",\+, <,>,\),\*,\-,%]? # optionally one of these symbols
$ # match to the end of the string
Much of this is poking about matching stuff around the currency amount, so you could reduce that.

Related

Get all prices with $ from string into an array in Javascript

var string = 'Our Prices are $355.00 and $550, down form $999.00';
How can I get those 3 prices into an array?
The RegEx
string.match(/\$((?:\d|\,)*\.?\d+)/g) || []
That || [] is for no matches: it gives an empty array rather than null.
Matches
$99
$.99
$9.99
$9,999
$9,999.99
Explanation
/ # Start RegEx
\$ # $ (dollar sign)
( # Capturing group (this is what you’re looking for)
(?: # Non-capturing group (these numbers or commas aren’t the only thing you’re looking for)
\d # Number
| # OR
\, # , (comma)
)* # Repeat any number of times, as many times as possible
\.? # . (dot), repeated at most once, as many times as possible
\d+ # Number, repeated at least once, as many times as possible
)
/ # End RegEx
g # Match all occurances (global)
To match numbers like .99 more easily I made the second number mandatory (\d+) while making the first number (along with commas) optional (\d*). This means, technically, a string like $999 is matched with the second number (after the optional decimal point) which doesn’t matter for the result — it’s just a technicality.
A non-regex approach: split the string and filter the contents:
var arr = string.split(' ').filter(function(val) {return val.startsWith('$');});
Use match with regex as follow:
string.match(/\$\d+(\.\d+)?/g)
Regex Explanation
/ : Delimiters of regex
\$: Matches $ literal
\d+: Matches one or more digits
()?: Matches zero or more of the preceding elements
\.: Matches .
g : Matches all the possible matching characters
Demo
This will check if there is a possible decimal digits following a '$'

Livecycle RegExp - trouble with decimal

Within Livecycle, I am validating that the number entered is a 0 through 10 and allows quarter hours. With the help of this post, I've written the following.
if (!xfa.event.newText.match(/^(([10]))$|^((([0-9]))$|^((([0-9]))\.?((25)|(50)|(5)|(75)|(0)|(00))))$/))
{
xfa.event.change = "";
};
The problem is periods are not being accepted. I have tried wrapping the \. in parenthesis but that did not work either. The field is a text field with no special formatting and the code in the change event.
Yikes, that's a convoluted regex. This can be simplified a lot:
/^(?:10|[0-9](?:\.(?:[27]?5)?0*)?)$/
Explanation:
^ # Start of string
(?: # Start of group:
10 # Either match 10
| # or
[0-9] # Match 0-9
(?: # optionally followed by this group:
\. # a dot
(?:[27]?5)? # either 25, 75 or 5 (also optional)
0* # followed by optional zeroes
)? # As said before, make the group optional
) # End of outer group
$ # End of string
Test it live on regex101.com.

Space in string allowed, but not at first or last position

For a form validation I've to check input with javascript for valid names
The string has to fit the following pattern.
I may not start or end with a space
It may contain spaces
It may contain capital en lowercase letters, inclusive ê è en such
It may symbols like - ' "
It must contain at least 1 character
This RegExp does the job almost:
[a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð ,.'-]
But this RegExp doesn't check for spaces at start of end.
Which JS RegExp requires the requirements mentioned above?
Thanks in advance
Here is my take on the topic:
if (subject.match(/^(?=\S+)(?=[a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð ,.'-]*$).*(?=\S).$/)) {
// Successful match
}
It basically says, start with at least something which isn't a space. So here goes conditions 1 and 5.
Then make sure that the whole thing consists of only allowed characters. Here goes all your other conditions.
Then make sure that there is at least a non space character, match it and then match tne end.
More details:
"
^ # Assert position at the beginning of the string
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
\S # Match a single character that is a “non-whitespace character”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
[a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð ,.'-] # Match a single character present in the list below
# A character in the range between “a” and “z”
# A character in the range between “A” and “Z”
# One of the characters “àáâäãåèéêëìíîïòóôöõøùúûüÿýñçcšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆCŠŽ?ð ,.”
# The character “'”
# The character “-”
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
. # Match any single character that is not a line break character
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
\S # Match a single character that is a “non-whitespace character”
)
. # Match any single character that is not a line break character
$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
You need to use the RegExp ^ and $ codes, which specify the start and ending respectively.
See more documentation about this.
Hope this helps!
Try this
^(?! )[a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð ,.'-]*[a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð,.'-]$
See it here on Regexr
^ anchors the pattern to the start of the string
$anchors the pattern to the end of the string
(?! ) is a negative lookahead that ensures, that its not starting with a space
Then there follows your character class with a * quantifier, means 0 or more times. At last there is your class once more, but without space, this is to ensure that it does not end with space.
Its a pity that Javascript regexes doesn't have Unicode support, and does not allow \p{L} for all kind of letters.

Validate currency amount using regular expressions in JavaScript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's a C# regular expression that'll validate currency, float or integer?
How can I validate currency amount using regular expressions in JavaScript?
Decimals separator: ,
Tens, hundreds, etc. separator: .
Pattern: ###.###.###,##
Examples of valid amounts:
1
1234
123456
1.234
123.456
1.234.567
1,23
12345,67
1234567,89
1.234,56
123.456,78
1.234.567,89
EDIT
I forgot to mention that the following pattern is also valid: ###,###,###.##
Based solely on the criteria you gave, this is what I came up with.
/(?:^\d{1,3}(?:\.?\d{3})*(?:,\d{2})?$)|(?:^\d{1,3}(?:,?\d{3})*(?:\.\d{2})?$)/
http://refiddle.com/18u
It is ugly, and it will only get worse as you find more cases that need to be matched. You'd be well served to find and use some validation library rather than try to do this all yourself, especially not in a single regular expression.
Updated to reflect added requirements.
Updated again in regard to comment below.
It would match 123.123,123 (three trailing digits instead of two) because it would accept either comma or period as both the thousands and decimal separators. To fix that, I've now essentially doubled up the expression; either it matches the whole thing with commas for separators and a period as the radix point, or it matches the whole thing with periods for separators and a comma as the radix point.
See what I mean about it getting messier? (^_^)
Here's the verbose explanation:
(?:^ # beginning of string
\d{1,3} # one, two, or three digits
(?:
\.? # optional separating period
\d{3} # followed by exactly three digits
)* # repeat this subpattern (.###) any number of times (including none at all)
(?:,\d{2})? # optionally followed by a decimal comma and exactly two digits
$) # End of string.
| # ...or...
(?:^ # beginning of string
\d{1,3} # one, two, or three digits
(?:
,? # optional separating comma
\d{3} # followed by exactly three digits
)* # repeat this subpattern (,###) any number of times (including none at all)
(?:\.\d{2})? # optionally followed by a decimal perioda and exactly two digits
$) # End of string.
One thing that makes it look more complicated is all the ?: in there. Normally a regular expression captures (returns matches for) all of the subpatterns too. All ?: does is say to not bother to capture the subpattern. So technically, the full thing would still match your entire string if you took all of the ?: out, which looks a bit clearer:
/(^\d{1,3}(\.?\d{3})*(,\d{2})?$)|(^\d{1,3}(,?\d{3})*(\.\d{2})?$)/
Also, regular-expressions.info is a great resource.
This works for all your examples:
/^(?:\d+(?:,\d{3})*(?:\.\d{2})?|\d+(?:\.\d{3})*(?:,\d{2})?)$/
As a verbose regex (not supported in JavaScript, though):
^ # Start of string
(?: # Match either...
\d+ # one or more digits
(?:,\d{3})* # optionally followed by comma-separated threes of digits
(?:\.\d{2})? # optionally followed by a decimal point and exactly two digits
| # ...or...
\d+ # one or more digits
(?:\.\d{3})* # optionally followed by point-separated threes of digits
(?:,\d{2})? # optionally followed by a decimal comma and exactly two digits
) # End of alternation
$ # End of string.
This handles everything above except for the (just added?) 123.45 case:
function foo (s) { return s.match(/^\d{1,3}(?:\.?\d{3})*(?:,\d\d)?$/) }
Do you need to handle multiple separator formats?

Regex validation for comma separated string

I need to validate and input string client side.
Here is an example of the string:
1:30-1:34, 1:20-1:22, 1:30-1:37,
It's basically time codes for a video.
Can this be done with regex?
Banging my head against the wall...
^(?:\b\d+:\d+-\d+:\d+\b(?:, )?)+$
would probably work; at least it matches your example. But you might need to add a few edge cases to make the rules for matching/not matching clearer.
^ # Start of string
(?: # Try to match...
\b # start of a "word" (in this case, number)
\d+ # one or more digits
: # a :
\d+ # one or more digits
- # a dash
\d+ # one or more digits
: # a :
\d+ # one or more digits
\b # end of a "word"
(?:, )? # optional comma and space
)+ # repeat one or more times
$ # until the end of the string
The following is a simple representation. I have assumed that the string has the exact same form as you have shown. This may be a good starting point for you. I'll improve the regex if you provide more specific requirements.
([0-9]+:[0-9]{1,2}-[0-9]+:[0-9]{1,2},\w*)+
Explanation (inspired from Tim above)
[0-9]+   #One ore more digits
:      # A colon
[0-9]{1,2}  #A single digit or a pair of digits
-       #A dash
,       #A comma
\w*      #Optional whitespace

Categories

Resources