tags:

views:

108

answers:

3

I need a regex which will allow only A-Z, a-z, 0-9, the _ character, and dot (.) in the input. I tried:

[A-Za-z0-9_.]

But it did not work. How can I fix it?

+11  A: 
^[A-Za-z0-9_.]+$

From beginning until the end one or more of these characters

Ikke
+1, taken my answer out, clearly wrong
Joel Goodwin
Can also be `^[\w.]+$`, thought that doesn't work everywhere.
Kobi
@Kobi: it works almost everywhere, just differently :)
SilentGhost
+2  A: 

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

Pete Duncanson
A: 

Maybe, you need to specify more exactly what didn't work and in what environment you are.

As to the claim that the dot is special in a charackter class, this is not true in every programming environment. For example the following perl script

use warnings;
use strict;

my $str = '!!!.###';
$str =~ s/[A-Za-z_.]/X/g;
print "$str\n";

produces

!!!X###
René Nyffenegger