I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.
To check the entire string and not allow empty strings, try
^[A-Za-z0-9_]+$
use lookaheads to do the "at least one" stuff. Trust me it's much easier.
Here's an example that would require 1-10 characters, containing at least one digit and one letter:
^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$
NOTE: could have used \w but then ECMA/Unicode considerations come into play increasing the character coverage of the \w "word character".
I believe you are not taking Latin and Unicode characters in your matches. For example, if you need to take "ã" or "ü" chars, the use of "\w" won't work.
You can, alternatively, use this approach:
^[A-ZÀ-Ýa-zà-ý0-9_]+$
Hope it helps!
The following regex matches alphanumeric characters and underscore:
^[a-zA-Z0-9_]+$
For example, in Perl:
#!/usr/bin/perl -w
my $arg1 = $ARGV[0];
# check that the string contains *only* one or more alphanumeric chars or underscores
if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
print "Failed.\n";
} else {
print "Success.\n";
}
How about:
^([A-Za-z]|[0-9]|_)+$
...if you want to be explicit, or:
^\w+$
...if you prefer concise (Perl syntax).
This should work in most of the cases.
/^[\d]*[a-z_][a-z\d_]*$/gi
And by most I mean,
abcd True
abcd12 True
ab12cd True
12abcd True
1234 False
^ ... $
- match the pattern starting and ending with[\d]*
- match zero or more digits[a-z_]
- match an alphabet or underscore[a-z\d_]*
- match an alphabet or digit or underscore/gi
- match globally across the string and case-insensitive