tags:

views:

119

answers:

5

I use this condition to check if the value is alphanumeric values:

$value =~ /^[a-zA-Z0-9]+$/

How can I modify this regex to account for a possible dot . in the value without accepting any other special characters?

+7  A: 
$value =~ /^[a-zA-Z0-9.]+$/
S.Mark
Shouldn't that be `\.`?
cmptrgeekken
$value =~ /^[a-zA-Z0-9.]+$/works for me, what would \. change?
goe
@cmptrgeeken: Dots aren't special inside character classes. `[.]`
Christoffer Hammarström
. usually means "match any character" in regexps. It doesn't mean that in character classes, though (what would be the point of the character class in that case?) so @cmptrgeekken is mistaken, but that's the idea he was basing his question on.
jemfinch
Aha, guess that makes sense ... guess I'm just used to always escaping my period. Good to know it's not always necessary.
cmptrgeekken
@goe, `.` means any character, but inside `[]`, its just a dot. so for your case, `.` or `\.` , they are the same
S.Mark
@cmptrgeekken: in character class (square brackets), all characters are literal unless, along with an escape they form a class specifier (`\s` or `\p{...}`) or an ansi class (`[:...:]`), so it's mainly the escape `'\\' ` and the square brackets themselves. Although, sometimes you will find that you need to escape the `$` because of interpolation of perl internal globals. (I've had a lot of fun with classes like `qr/[#@$]/` where perl wants to sub the [patch level](http://perldoc.perl.org/perlvar.html) and blow away the end of the class definition.
Axeman
+2  A: 

Using the posix character class, one char shorter :)

value =~ /^[[:alnum:].]+$/;
eugene y
I think you want `[:alnum:]`, it includes digits.
Ven'Tatsu
@Ven'Tatsu: thanks, corrected.
eugene y
A: 

Look at perl regular expressions

\w  Match "word" character (alphanumeric plus "_")


$value =~ /^[\w+.]\.*$/;
Space
`\w` is alphanumeric plus "_".
eugene y
Agreed with @eugene. You have to be careful with \w because of those pesky '_' characters. They are part of Perl's number interpretation as a thousand's separator, and possibly because of variable names but not used in normal text.
Greg
+2  A: 

Don't forget the /i option and the \d character class.

$value =~ /^[a-z\d.]+$/i
FM
+1  A: 

If you don't want to allow any characters other than those allowed in the character class, you shouldn't use the $ end of line anchor since that allows a trailing newline. Use the absolute end-of-string anchor \z instead:

 $value =~ /^[a-z0-9.]+\z/i;
brian d foy