# Regular expression

**URL:** <https://www.ruby-forum.com/t/regular-expression/145165>\
**Category:** Ruby\
**Created:** [August 6, 2008, 4:28pm UTC](https://www.ruby-forum.com/t/regular-expression/145165 "2008-08-06T16:28:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vanight](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/a698b9/32.png) [@vanight](https://www.ruby-forum.com/u/vanight)\
**Post date:** [August 6, 2008, 4:28pm UTC](https://www.ruby-forum.com/t/regular-expression/145165/1 "2008-08-06T16:28:35Z")

</div>

Hi,  
I need a regular expression for a filename :  
it must be composed with the following letters :

a to z  
A to Z  
0 to 9  
dash sign -  
underscore sign \_

then how can I compare a string with it :

mystring =~ /myregex/ #return true or false

does it works like that ?

---

<div class="post-metadata">

**Author:** ![vanight](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/a698b9/32.png) [@vanight](https://www.ruby-forum.com/u/vanight)\
**Post date:** [August 6, 2008, 4:55pm UTC](https://www.ruby-forum.com/t/regular-expression/145165/2 "2008-08-06T16:55:02Z")

</div>

On Aug 6, 2008, at 10:26 AM, David N. wrote:

> then how can I compare a string with it :
> 
> mystring =~ /myregex/ #return true or false
> 
> does it works like that ?

Yes. Although String#=~ returns the position the match starts, or nil  
if there is no match. If the right-hand-side is not a Regexp, invokes  
obj.=~, passing str as an argument. The default =~ in Object returns  
false.

Since a Fixnum is not nil or false, it will be “true” and both nil and  
false will be “false”.

The only other issue is that the dash (hyphen-minus; ‘-’) is special  
inside a character class of regular expressions. For example, if you  
wanted to match a dash or digit, you could use /[-0-9]/ so the -  
appearing first is not treated as a character range operation.

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
