This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 4 years ago.
I want to validate user's input and i use the following (which works fine) as regex.
pattern = /^[a-zA-Z0-9 .,!?;-]+$/;
But when i try with all the characters i want, which is this.
pattern = /^[a-zA-Z0-9 .,!?;-:()#'+=/]+$/;
It doesn't work and I dont know why. Also, I would appreciate it a lot if you explained to me what's the difference when I add the ^ and the +$. Also i have tried using \s instead of space, and it still doesn't work(I prefer just space because i want to restrict line change).
The "hyphen-minus" character, -, has special meaning within a character set (a set of characters between [ and ]). It, -, defines a range of characters. Most of the time in a character set that you want the - to represent itself, you need to use \- to escape its special meaning. In your use, - needs to be escaped \- when used between ; and :.
Working:
pattern = /^[a-zA-Z0-9 .,!?;\-:()#'+=/]+$/;
If you actually want the range of characters between : and ;, then you need to specify the one that has a lower character code (Ascii code chart, or Unicode) first. In this case, that means :-; as : comes before ;:
Show :-; range is valid:
pattern = /^[a-zA-Z0-9 .,!?:-;()#'+=/]+$/;
The same error would be generated if you were to try to specify a range such as z-a.
Show same error with range of z-a:
pattern = /^[z-aA-Z0-9 .,!?:-;()#'+=/]+$/;
The - does not take on its special meaning if it is the first or last character in the character set.
Note: In some regular expression implementations, the - does have its special meaning if you try to use it as the last character in the character set. You are better off just being in the habit of escaping it with \-.
Using - as first or last character in character set:
pattern = /^[-a-zA-Z0-9 .,!?;:()#'+=/]+$/;
pattern = /^[a-zA-Z0-9 .,!?;:()#'+=/-]+$/;
Original code with error:
pattern = /^[a-zA-Z0-9 .,!?;-:()#'+=/]+$/;
Related
I'm working with the following regex:
var currentVal = $(this).val();
//making sure it's only numbers, decimals, and commas
var isValid = /^[0-9,.]*$/.test(currentVal);
and I'm trying to modify it so that it disallows spaces as well. I tried adding /s within the regex but it still allows it. Newer to regex, gets confusing quick
The brackets [] in your regex form a character class. ^ means start of string and $ means end of string with * applying the character class greedily multiple times. As it is written it should only allow characters specified in the class 0 through 9, comma, and period characters. If you tried adding in \s you would be also allowing for any whitespace characters in your character class, and thus cause your problem.
console.log(/^[0-9,.]*$/.test("123 903"));
I am facing an issue with a regular expression while trying to block any string which has minus(-) in the beginning of some white listed characters.
^(?!-.*$).([a-zA-Z0-9-:#\\,()\\/\\.]+)$
It is blocking minus(-) at place and allowing it any where in the character sequence but this regex is not working if the passed string is single character.
For e.g A or 9 etc.
Please help me out with this or give me a good regex to do the task.
Your pattern requires at least 2 chars in the input string because there is a dot after the first lookahead and then a character class follows that has + after it (that is, at least 1 occurrence must be present in the string).
So, you need to remove the dot. Also, you do not need to escape any special char inside a character class. Besides, to avoid matching strings atarting with - a mere (?!-) will suffice, no need adding .*$ there. You may use
^(?!-)[a-zA-Z0-9:#,()/.-]+$
See the regex demo. Remember to escape / if used in a regex literal notation in JavaScript, there is no need to escape it in a constructor notation or in a Java regex pattern.
Details
^ - start of a string
(?!-) - cannot start with -
[a-zA-Z0-9:#,()/.-]+ - 1 or more ASCII letters, digits and special chars defined in the character class (:, #, ,, (, ), /, ., -)
$ - end of string.
If i understand correctly, and you don't want a minus at the beginning, does ^[^-].* work as a regex for you? Java's "matches" would return false if it starts with minus
There is a method in a String class that provides you exactly what you are asking for - it's a startsWith() method - you could use this method in your code like this (you can translate it as "If the given String doesn't start with -, doSomething, in other case do the else part, that can contain some code or might be empty if you want nothing to be done if the given String starts with - ") :
if(!(yourString.startsWith("-"))) {
doSomething()
} else {
doNothingOrProvideAnyInformationAboutWrongInput()
}
I think that it can help you.
^(?!-).*[a-zA-Z0-9-:#\\,()\/\\.]+$
I have constructed the following Regex, which allows strings that only satisfy all three conditions:
Allows alphanumeric characters.
Allows special characters defined in the Regex.
String length must be min 8 and max 20 characters.
The Regex is:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$"
I use the following Javascript code to verify input:
var regPassword = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$");
regPassword.test(form.passwordField.value);
The test() method returns false for such inputs as abc123!ZXCBN. I have tried to locate the problem in the Regex without any success. What causes the Regex validation to fail?
I see two major problems. One is that inside a string "...", backslashes \ have a special meaning, independent of their special meaning inside a regex. In particular, \d ends up just becoming d — not what you want. The best fix for that is to use the /.../ notation instead of new RegExp("..."):
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$/;
The other problem is that your regex doesn't match your requirements.
Actually, the requirements that you've stated don't really make sense, but I'm guessing you want something like this:
Must contain at least one lowercase letter, at least one uppercase letter, at least one digit, and at least one of the special characters $#$!%*?&.
Can only contain lowercase letters, uppercase letters, digits, and the special characters $#$!%*?&.
Total length must be between 8 and 20 characters, inclusive.
If so, then you've managed #1 and #2, but forgot about #3. Right now your regex demands that the length be exactly 1. To fix this, you need to add {8,20} after the [A-Za-z\d$#$!%*?&] part:
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,20}$/;
This question already has answers here:
Get final special character with a regular expression
(2 answers)
Closed 8 years ago.
I need to remove certain special characters from a string.
For the same am using
replace(/[()-/.]/gi, '');
This is working fine , however I realized that it also removes '*'.Any idea why??
If I remove '.' from the expression it's working fine ,so I guess that is creating some issue which am not sure of
Problem is unescaped hyphen appearing in the middle. Make it like this:
replace(/[()\/.-]/gi, '');
When an unescaped hyphen appears in the middle of the character class it acts as a range
) is ascii 41
/ is ascii 47
* is ascii 42 hence your regex negates * since - acts on all characters in the range 41-47
The hyphen needs to be escaped because of its position inside of the character class. You can as well remove the i (case-insensitive) flag, it is not necessary because you don't include proper characters.
/[()\-\/.]/g
Note: Inside of a character class the hyphen has special meaning. You can place it as the first or last character of the class. In some regex implementations, you can also place directly after a range. If you place the hyphen anywhere else you need to precede it with a backslash in order to add it to your character class.
This question already has answers here:
Why is this regex allowing a caret?
(3 answers)
Closed 1 year ago.
I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed). My code is:
var value = userInput;
var pattern = /[^A-z0-9 "!&,'\-]/;
if(patt.test(value) == true) then do something
It works fine and excludes the letters that I don't want the user to enter except the square bracket and the caret symbols. From all the javascript regex tutorials that i have read they are special characters - the brackets meaning any character between them and the caret in this instance meaning any character not in between the square brackets. I have searched here and on google for an explanation as to why these characters are also accepted but can't find an explanation.
So can anyone help, why does my input accept the square brackets and the caret?
The reason is that you are using A-z rather than A-Za-z. The ascii range between Z (0x5a) and a (0x61) includes the square brackets, the caret, backquote, and underscore.
Your regex is not in line with what you said:
I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed
If you want to accept only those characters, you need to remove the caret:
var pattern = /^[A-Za-z0-9 "!&,'\\-]+$/;
Notes:
A-z also includesthe characters: [\]^_`.
Use A-Za-z or use the i modifier to match only alphabets:
var pattern = /^[a-z0-9 "!&,'\\-]+$/i;
\- is only the character -, because the backslash will act as special character for escaping. Use \\ to allow a backslash.
^ and $ are anchors, used to match the beginning and end of the string. This ensures that the whole string is matched against the regex.
+ is used after the character class to match more than one character.
If you mean that you want to match characters other than the ones you accept and are using this to prevent the user from entering 'forbidden' characters, then the first note above describes your issue. Use A-Za-z instead of A-z (the second note is also relevant).
I'm not sure what you want but I don't think your current regexp does what you think it does:
It tries to find one character is not A-z0-9 "!&,'\- (^ means not).
Also, I'm not even sure what A-z matches. It's either a-z or A-Z.
So your current regexp matches strings like "." and "Hi." but not "Hi"
Try this: var pattern = /[^\w"!&,'\\-]/;
Note: \w also includes _, so if you want to avoid that then try
var pattern = /[^a-z0-9"!&,'\\-]/i;
I think the issue with your regex is that A-z is being understood as all characters between 0x41 (65) and 0x7A (122), which included the characters []^_` that are between A-Z and a-z. (Z is 0x5A (90) and a is 0x61 (97), which means the preceding characters take up 0x5B thru 0x60).