Regular expression for allow - not more then 2 times - javascript

i am using ^(^[a-z]?[a0-z9]+[.|-][a0-z9]+[a-z]+[.|-][a0-z9]+[a-z]?$)+$ , this force user type 2 hyphen(-) in his expression ....
But i need that regular expression can allow maximum 2 hypen and minimum one hyphen in his expression....

This is a simple re implementation.
/^[^-]+(-[^-]+){1,2}$/
And the test result:
"123".match(/^[^-]+(-[^-]+){1,2}$/)
null
"123-123".match(/^[^-]+(-[^-]+){1,2}$/)
["123-123", "-123"]
"123-123-123".match(/^[^-]+(-[^-]+){1,2}$/)
["123-123-123", "-123"]
"123-123-123-123".match(/^[^-]+(-[^-]+){1,2}$/)
null
And if you just copy one from other, then you should try to write one by yourself.
If not, you should delete it and restart.

^[^-]*-+[^-]*-{0,1}[^-]*$
String1: abc-pqr,
String2: aaa-bbb,
String3 aaa-bbb-ccc-ddd,
where String 1 and 2 are valid and 3 is invalid?
This allows String 1 and 2. But not 3.

This regex should work...
/^[^-]*-[^-]*-[^-]*$/
It works by capturing anything except a hyphen (zero or more times), then a hyphen, then anything else again, then another hyphen, then anything else. It has a start and end marker to ensure that the whole string does not contain any more hyphens.
Breaks down like this...
/ # begin regex
^ # start of string
[^-]* # not hyphen ([^-]), zero or more times (*)
- # hyphen
[^-]* # not hyphen ([^-]), zero or more times (*)
- # hyphen
[^-]* # not hyphen ([^-]), zero or more times (*)
$ # end of string
/ # end regex

Related

Using RegExp to test words for letter count

I've been trying to use RegExp in JS to test a string for a certain count of a substrings. I would like a purely RegExp approach so I can combine it with my other search criteria, but have not had any luck.
As a simple example I would like to test a word if it has exactly 2-3 as.
case
test string
expected result
1
cat
false
2
shazam
true
3
abracadabra
false
Most of my guesses at regex fail case 3. Example: ^(?<!.*a.*)((.*a.*){2,3})(?!.*a.*)$
Could use this regex.
With any other character, including whitespace.
^[^a]*(?:a[^a]*){2,3}$
or if using multi-lines and don't want to span.
^[^a\r\n]*(?:a[^a\r\n]*){2,3}$
^ # Begin
[^a]* # optional not-a
(?: # Grp
a # single a
[^a]* # optional not-a
){2,3} # Get 2 or 3 a only
$ # End
https://regex101.com/r/O3SYKx/1

JS regex to match a username with specific special characters and no consecutive spaces

I am pretty new to this reg ex world. Struck up with small task regarding Regex.
Before posting new question I have gone thru some answers which am able to understand but couldnt crack the solution for my problem
Appreciate your help on this.
My Scenario is:
Validating the Username base on below criteria
1- First character has to be a-zA-Z0-9_# (either of two special characters(_#) or alphanumeric)
2 - The rest can be any letters, any numbers and -#_ (either of three special characters and alphanumeric).
3 - BUT no consecutive spaces between words.
4- Max size should be 30 characters
my username might contain multiple words seperated by single space..for the first word only _# alphanumeric are allowed and for the second word onwards it can contain _-#aphanumeric
Need to ignore the Trailing spaces at the end of the username
Examples are: #test, _test, #test123, 123#, test_-#, test -test1, #test -_#test etc...
Appreciate your help on this..
Thanks
Arjun
Here you go:
^(?!.*[ ]{2,})[\w#][-#\w]{0,29}$
See it working on regex101.com.
Condition 3 is ambigouus though as you're not allowing spaces anyway. \w is a shortcut for [a-zA-Z_], (?!...) is called a neg. lookahead.
Broken down this says:
^ # start of string
(?!.*[ ]{2,}) # neg. lookahead, no consecutive spaces
[\w#] # condition 1
[-#\w]{0,29} # condition 2 and 4
$ # end of string
This might work ^(?=.{1,30}$)(?!.*[ ]{2})[a-zA-Z0-9_#]+(?:[ ][a-zA-Z0-9_#-]+)*$
Note - the check for no consecutive spaces (?! .* [ ]{2} ) is not really
necessary since the regex body only allows a single space between words.
It is left in for posterity, take it out if you want.
Explained
^ # BOS
(?= .{1,30} $ ) # Min 1 character, max 30
(?! .* [ ]{2} ) # No consecutive spaces (not really necessary here)
[a-zA-Z0-9_#]+ # First word only
(?: # Optional other words
[ ]
[a-zA-Z0-9_#-]+
)*
$ # EOS

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 '$'

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?

Categories

Resources