Regex Expression To Match Special Characters And Numbers - javascript

I'm looking for a regexp to see if a string contains any special characters, numbers or anything else but letters.
For example I have a string "This is a 5 string #". Now I would need a regexp to see if this string contains any special characters like # or numbers like 5.
I'm not familiar with using regexp approaches.

you can use .test() method
if ("This is a 5 string #".test(/[^a-z]/i)) { ... }
this will find if some symbols different from a-z and A-Z are inside the string. Note also that this regexp won't accept accented letters. in that case you will need a more refined regexp like
/[^a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF]/
see a unicode table to choose what symbols are acceptable in your string
http://unicode.org/charts/

The basics you want is something like /^[a-zA-Z]+$/
this will tell you if your string as any charachters of a to z upper and lowercase.
There are tons off resources online to learn more about regex, a good resource is http://www.regular-expressions.info/reference.html

Related

Regex - must contain number and must not contain special character

I want to check by regex if:
String contains number
String does not contain special characters (!<>?=+#{}_$%)
Now it looks like:
^[^!<>?=+#{}_$%]+$
How should I edit this regex to check if there is number anywhere in the string (it must contain it)?
you can add [0-9]+ or \d+ into your regex, like this:
^[^!<>?=+#{}_$%]*[0-9]+[^!<>?=+#{}_$%]*$
or
^[^!<>?=+#{}_$%]*\d+[^!<>?=+#{}_$%]*$
different between [0-9] and \d see here
Just look ahead for the digit:
var re = /^(?=.*\d)[^!<>?=+#{}_$%]+$/;
console.log(re.test('bob'));
console.log(re.test('bob1'));
console.log(re.test('bob#'))
The (?=.*\d) part is the lookahead for a single digit somewhere in the input.
You only needed to add the number check, is that right? You can do it like so:
/^(?=.*\d)[^!<>?=+#{}_$%]+$/
We do a lookahead (like peeking at the following characters without moving where we are in the string) to check to see if there is at least one number anywhere in the string. Then we do our normal check to see if none of the characters are those symbols, moving through the string as we go.
Just as a note: If you want to match newlines (a.k.a. line breaks), then you can change the dot . into [\W\w]. This matches any character whatsoever. You can do this in a number of ways, but they're all pretty much as clunky as each other, so it's up to you.

Identifying special non alphanumeric characters in a string

Im working on a password validation that should only allow a-z 0-9 and these characters "!"#$%&'()*+,-./:;<=>?#[\]^_{|}~`
I tried using a regex but I'm not too good with them and I wasnt sure if this is even possible or if Im not escaping the correct characters.
var allowedCharacters = /^[A-Za-Z0-9!"#$%&'()*+,-.\/:;<=>?#[\\]^_`{|}~]+$/;
if (!s.value.match(allowedCharacters)){
displayIllegalTextError();
return false;
}
You need to place the dash at the start or end of the regex, or it will try to create a character range (,-.). Then, a-Z isn't a valid range, you probably meant a-z. Also, you need to escape the closing brackets:
/^[A-Za-z0-9!"#$%&'()*+,.\/:;<=>?#[\\\]^_`{|}~-]+$/
Looking over the ascii chart here I see your regex could be reduced to this character range:
/^[\x21-\x7e]+$/
If you just want to learn special behavior of character classes, you should read up
on it via regex basic tutorials.
Note that class behavior differs amongst the different flavors.
Simpler and more to the point using unicode: ^[\u0021-\u007E]+$.
/^[\u0021-\u007E]+$/.test('MyPassword!') // returns true
/^[\u0021-\u007E]+$/.test('MyPassword™') // returns false
Now if you would like to go a few steps further and actually create a more complex validation such as: minimum length 8 characters and at least one lowercase, one uppercase, one digit and one special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])[\u0021-\u007E]{8,}$

Javascript match function for special characters

I am working on this code and using "match" function to detect strength of password. how can I detect if string has special characters in it?
if(password.match(/[a-z]+/)) score++;
if(password.match(/[A-Z]+/)) score++;
if(password.match(/[0-9]+/)) score++;
If you mean !##$% and ë as special character you can use:
/[^a-zA-Z ]+/
The ^ means if it is not something like a-z or A-Z or a space.
And if you mean only things like !#$&$ use:
/\W+/
\w matches word characters, \W matching not word characters.
You'll have to whitelist them individually, like so:
if(password.match(/[`~!##\$%\^&\*\(\)\-=_+\\\[\]{}/\?,\.\<\> ...
and so on. Note that you'll have to escape regex control characters with a \.
While less elegant than /[^A-Za-z0-9]+/, this will avoid internationalization issues (e.g., will not automatically whitelist Far Eastern Language characters such as Chinese or Japanese).
you can always negate the character class:
if(password.match(/[^a-z\d]+/i)) {
// password contains characters that are *not*
// a-z, A-Z or 0-9
}
However, I'd suggest using a ready-made script. With the code above, you could just type a bunch of spaces, and get a better score.
Just do what you did above, but create a group for !##$%^&*() etc. Just be sure to escape characters that have meaning in regex, like ^ and ( etc....
EDIT -- I just found this which lists characters that have meaning in regex.
if(password.match(/[^\w\s]/)) score++;
This will match anything that is not alphanumeric or blank space. If whitespaces should match too, just use /[^\w]/.
As it look from your regex, you are calling everything except for alphanumeric a special character. If that is the case, simply do.
if(password.match(/[\W]/)) {
// Contains special character.
}
Anyhow how why don't you combine those three regex into one.
if(password.match(/[\w]+/gi)) {
// Do your stuff.
}
/[^a-zA-Z0-9 ]+/
This will accept only special characters and will not accept a to z & A to Z 0 to 9 digits

Writing a Javascript regex that includes special reserved characters

I'm writing a function that takes a prospective filename and validates it in order to ensure that no system disallowed characters are in the filename. These are the disallowed characters: / \ | * ? " < >
I could obviously just use string.indexOf() to search for each special char one by one, but that's a lot longer than it would be to just use string.search() using a regular expression to find any of those characters in the filename.
The problem is that most of these characters are considered to be part of describing a regular expression, so I'm unsure how to include those characters as actually being part of the regex itself. For example, the / character in a Javascript regex tells Javascript that it is the beginning or end of the regex. How would one write a JS regex that functionally behaves like so: filename.search(\ OR / OR | OR * OR ? OR " OR < OR >)
Put your stuff in a character class like so:
[/\\|*?"<>]
You're gonna have to escape the backslash, but the other characters lose their special meaning. Also, RegExp's test() method is more appropriate than String.search in this case.
filenameIsInvalid = /[/\\|*?"<>]/.test(filename);
Include a backslash before the special characters [\^$.|?*+(){}, for instance, like \$
You can also search for a character by specified ASCII/ANSI value. Use \xFF where FF are 2 hexadecimal digits. Here is a hex table reference. http://www.asciitable.com/ Here is a regex reference http://www.regular-expressions.info/reference.html
The correct syntax of the regex is:
/^[^\/\\|\*\?"<>]+$/
The [^ will match anything, but anything that is matched in the [^] group will return the match as null. So to check for validation is to match against null.
Demo: jsFiddle.
Demo #2: Comparing against null.
The first string is valid; the second is invalid, hence null.
But obviously, you need to escape regex characters that are used in the matching. To escape a character that is used for regex needs to have a backslash before the character, e.g. \*, \/, \$, \?.
You'll need to escape the special characters. In javascript this is done by using the \ (backslash) character.
I'd recommend however using something like xregexp which will handle the escaping for you if you wish to match a string literal (something that is lacking in javascript's native regex support).

Difficulties with constructing this JavaScript regex

I would like to construct a regular expression that matches any letter (including accented and Greek), number, hyphens and spaces with a total allowed characters length between 3 and 50.
This is what I made:
[- a-zA-Z0-9çæœáééíóúžàèìòùäëïöüÿâêîôûãñõåøαβγδεζηθικλμνξοπρστυφχψωÇÆŒÁÉÍÓÚŽÀÈÌÒÙÄËÏÖÜŸÂÊÎÔÛÃÑÕÅØΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ]{3,50}
Now I wan't to adjust the expression so that it can't start with a hyphen or space. It will be used to validate a username.
I thought about using a negative lookbehind but these are the limitations:
JavaScript doesn't support a lookbehind.
The alternatives for a lookbehind aren't really applicable since they all depend on other JavaScript functions and I am bound to using the match function.
I hope there are any regular expression heroes here since it doesn't look simple.
I replaced your long character class with a-z for readability:
[a-z][- a-z]{2,49}
You could also match with your current regex and then make sure that the string does not match ^[ -] in another match.

Categories