What would be the correct Javascript RegExp to validate the following string "900 - 09 999"
The string should only allow digits from 0 to 9, an hyphen and a space.
Thanks in advance
Always be precise when you explain what you want your regex to validate. Are the spaces and hyphens optional or not? This stuff matters. Anyway, this validates the strict format:
"\d{3} \- \d{2} \d{3}"
And this a less strict one:
"\d{3} ?\-? ?\d{2} ?\d{3}"
If you use this:
inputField.value = inputField.value.replace(/\s*(\d\d\d)\s*-?\s*(\d\d)\s*(\d\d\d)\s*/, "$1 - $2 $3")
...it should both loosely validate AND reformat the value if it does not match perfectly.
broken down, the expression does the following:
\s* # match any amount of whitespace
(\d\d\d) # capture three digits
\s* # match any amount of whitespace
-? # match an optional hyphen
\s* # match any amount of whitespace
(\d\d) # capture two digits
\s* # match any amount of whitespace
(\d\d\d) # capture three digits
\s* # match any amount of whitespace
match means to find a set of characters that matches the expression
capture means to find a match, but store the match for later use
whitespace can be spaces, tabs or carriage return characters
any amount can mean zero or more
Related
I want regex which can fulfill below requirement:
Between 6 and 10 total characters
At least 1 but not more than 2 of the characters need to be alpha
The alpha characters can be anywhere in the string
We have tried this but not working as expected : (^[A-Z]{1,2}[0-9]{5,8}$)|(^[A-Z]{1}[0-9]{4,8}[A-Z]{1}$)|(^[0-9]{4,8}[A-Z]{1,2}$)|([^A-Z]{3}[0-9]{6,9})
Can anyone please help me to figure it out?
Thanks
You can assert the length of the string to be 6-10 char.
Then match at least a single char [A-Z] between optional digits, and optionally match a second char [A-Z] between optional digits.
^(?=[A-Z\d]{6,10}$)\d*[A-Z](?:\d*[A-Z])?\d*$
^ Start of string
(?=[A-Z\d]{6,10}$) Positive lookahead to assert 6-10 occurrences of A-Z or a digit
\d*[A-Z] Match optional digits and then match the first [A-Z]
(?:\d*[A-Z])? Optionally match optional digits and the second [A-Z]
\d* Match optional digits
$ End of string
See a regex demo.
One option is to use the following regular expression:
^(?=.*[a-z])(?!(?:.*[a-z]){3})[a-z\d]{6,10}$
with the case-indifferent flag i set.
Demo
This expression reads, "Match the beginning of the string, assert the string contains at least one letter, assert the string does not contain three letters and assert the string contains 6-10 characters, all being letters or numbers".
The various parts of the expression have the following functions.
^ # match the beginning of the string
(?= # begin a positive lookahead
.*[a-z] # match zero or more characters and then a letter
) # end positive lookahead
(?! # begin a negative lookahead
(?: # begin a non-capture group
.*[a-z] # match zero or more characters and then a letter
){3} # end non-capture group and execute it 3 times
) # end negative lookahead
[a-z\d]{6,10} # match 6-10 letters or digits
$ # match end of string
Note that neither of the lookaheads advances the string pointer maintained by the regex engine from the beginning of the string.
I have a requirement, where i have to validate a field in Excel.
Validations:
Field should start and end with [a-zA-Z0-9] but not with any special chars [-_]
It cannot contain "-" and "_" continuously more than once.
Example:
A--Badasd (Not allowed)
A__Bsdasdas (Not allowed)
A-_fdsfdsd (Not Allowed)
A_-sfsdfsdf (Not allowed)
A-B-adf (allowed)
A_b_adads (allowed)
I came up with this following regex, however, it doesn't seem to accept even the non-continuous entries of "-" and "_".
^[a-zA-z0-9]+(([\xFF01-\xFF5E]+|[\\-\\_])+)[a-zA-Z0-9]+$
[\xFF01-\xFF5E] is to not allow any double width characters, so please ignore it as it is working fine.
Any help would be greatly appreciable.
I can only suggest a lookahead based pattern (as [\xFF01-\xFF5E] matches _ and restricting it in JS regex will make the pattern more cumbersome):
/^[a-z0-9](?:(?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9])?$/i
See the regex demo.
This pattern will match strings of 1 char length, too, and will only match those strings starting and ending with an ASCII alphanumeric char and not having --, _-, -_ and __ in them.
If you want to "block" strings of length 1, i.e. set the minimum match length to 2, you should remove (?: and )? from the pattern above:
/^[a-z0-9](?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9]$/i
Details
^ - start of string
[a-z0-9] - an alphanumeric ASCII char
(?:(?!.*?[-_]{2})[\xFF01-\xFF5E_-]*[a-z0-9])? - an optional (1 or 0 occurrences) sequence of:
(?!.*?[-_]{2}) - a lookahead check that will fail the match if there are 2 consecutive - or _ anywhere after any 0+ chars other than line break chars
[\xFF01-\xFF5E-]* - any char in the \xFF01-\xFF5E range or/and -
[a-z0-9] - an alphanumeric ASCII char
$ - end of string.
I've got this RegEx which is used to validate what the user enters
It must be a value 8 - 16 characters long and can contain ONE of the certain special characters.
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~]).{8,16}$"
I'm not trying to show an alert if the user enters something that doesn't match the above. So a-z, A-Z, 0-9 and :;#~ are allowed but anything else shows an alert.
So Abcd1234# is OK, but if they enter Abcd1234!$ if will show the alert as ! & $ are not in the match.
I've tried adding ^ to the start of character match to try and negate them, but that didn't work.
What's the best way to do this?
It seems you only need to allow the characters mentioned in the lookaheads, create a character class with them and replace the last . with it:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~])[\da-zA-Z:;#~]{8,16}$/
^^^^^^^^^^^^^^
See the regex demo
The [\da-zA-Z:;#~]{8,16} pattern will match 8 to 16 chars that are either digits, ASCII letters, or :, ;, # or ~ symbols.
Details:
^ - start of string
(?=.*\d) - there must be a digit after any 0+ chars other than line break chars (a (?=\D*\d) will be more efficient as it is based on the contrast principle)
(?=.*[a-z]) - - there must be an ASCII lowercase letter after any 0+ chars other than line break chars (a (?=[^a-z]*[a-z]) will be more efficient)
(?=.*[A-Z]) - there must be an ASCII uppercase letter after any 0+ chars other than line break chars (a (?=[^A-Z]*[A-Z]) will be more efficient)
(?=.*[:;#~]) - there must be a :, ;, # or ~ after any 0+ chars other than line break chars (you may also use (?=[^:;#~]*[:;#~]))
[\da-zA-Z:;#~]{8,16} - 8 to 16 chars defined in the character class
$ - end of string.
HI I am new to regular expression, I tried creation regular expression based on below conditions:
Maximum 9 characters are allowed
First character must be upper case
Ending character must be 0-9
Must contain following special character ($,%,#)
/^[A-Z][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\d+$/
What is wrong in my regular expression?
^[A-Z](?=.*[#$%])[a-z0-9A-Z$#%]{1,7}\d$
You need to take the lookahead at the start.\d+ should be \d.{3,9} should be {1,7}
Breaking the regex down
/^[A-Z][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\d+$/
^ # Match the start of a string
[A-Z] # First character must be a capital letter
[a-z0-9A-Z$#%]{3,9} # The next 3-9 characters must be alphanumeric or one of $, # and %.
(?=.*[#$%]) # Look-ahead, requiring that some character be one of $, # and % (note that this is strictly after the 3-9 character check)
. # Match any character
\d+ # Match one or more numeric digits
$ # Match the end of the string
Therefore a string like "Aaaa$^55555555555555555" would be matched.
You need to change your look-ahead, probably moving it to before the 3-9 character check. You'll also want to make the length of that smaller, since you're explicitly allowing a capital letter as the first character and digit as the last character, so you'll probably want to match 1-7 characters instead of 3-9.
The regex I have is...
^[A-z0-9]*[A-z0-9\s]{0,20}[A-z0-9]*$
The ultimate goal of this regex is not to allow leading and trailing spaces, while limiting the characters that are entered to 20, which the above regex doesn't do a good job at.
I found a some questions similar to this and the closest one to this would be How to validate a user name with regex?, but it did not limit the number of chars. This did solve the problem of leading and trailing spaces.
I also saw a way using negation and another negative lookahead, but that didn't work out so well for me.
Is there a better way to write the regex above with the 20 character limit? The repeat of the allowed characters is pretty ugly especially when the list of the allowed characters are large and specific.
Update:
I like this one even better. We use a negative lookahead to make sure there isn't ^\s (whitespace at the beginning of the string) or \s$ whitespace at the end of the string. And then match 1 alphanumeric character. We repeat this 1-20 times.
/^(?:(?!^\s|\s$)[a-z0-9\s]){1,20}$/i
Demo
^ (?# beginning of string)
(?: (?# non-capture group for repetition)
(?! (?# begin negative lookahead)
^\s (?# whitespace at beginning of string)
| (?# OR)
\s$ (?# whitespace at end of string)
) (?# end negative lookahead)
[a-z0-9\s] (?# match one alphanumeric/whitespace character)
){1,20} (?# repeat this process 1-20 times)
$ (?# end of string)
Initial:
I use a negative lookahead at the beginning of the string ((?!...)) to make sure that we don't start off with whitespace. Then we check for 0-19 alphanumeric (case-insensitive thanks to i modifier) or whitespace characters. Finally, we make sure we end with a pure alphanumeric character (no whitespace) since we can't use lookbehinds in Javascript.
/^(?!\s)[a-z0-9\s]{0,19}[a-z0-9]$/i
Hmm, if you need to exclude the single character text, I would go with:
^[A-z0-9][A-z0-9\s]{0,18}[A-z0-9]$
If a single character is also acceptable:
^[A-z0-9](?:[A-z0-9\s]{0,18}[A-z0-9])?$
I think your regex limits the input to 22 characters, not 20.
Are you aware that character range [A-z] includes characters [\]^_`?
I think I'd do something like this:
input = input.trim().replace(/\s+/, ' ');
if (input.length > MAX_INPUT_LENGTH ||
! /^[a-z ]+$/i.match(input) ) {
# raise exception?
}
\S matches a non-whitespace character. Therefore this should match what you're looking for:
^\S.{0,18}\S$
That is, a non-space character \S, followed by up to 18 of any type of character . (space or not), and finally a non-space character.
The only limitation of the above regex is that the value must be at least 2 characters. If you need to allow 1 character, you can use:
^\S(.{0,18}\S)?$
If you're looking to validate a user name (as you implied but didn't explicitly state) you're probably looking to allow only numbers, letters, and underscores. In that case, ^\w{1,20}$ will suffice.
use this pattern ^(?!\s).{0,20}(?<!\s)$
^(?!\s) start of line does not see a space
.{0,20} followed by 0 to 20 characters
(?<!\s)$ ends with a character that is not a space
Demo
or this pattern ^(\S.{0,18}\S)?$
Demo