From: Holden Glova Date: 2001-12-26T13:43:17+09:00 Subject: [ruby-talk:29432] Re: Help with Regular Expression -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wed, 26 Dec 2001 17:11, Vincent Foley wrote: > Hi, > > I would like to know how I would check if a variable's content > matches a regular expression. Example (complete the code): > > [code] > #!/usr/bin/env ruby > > a = gets.chomp > > # Complete here. I want to know if a is an integer with regular > # expressions (/\d*/). Can I do that? How? > > [/code] Hi Vincent, You could try something along the lines of this: irb(main):010:0> a = "+232" "+232" irb(main):011:0> a =~ /^[+-]?\d+$/ 0 irb(main):012:0> a = "-232" "-232" irb(main):013:0> a =~ /^[+-]?\d+$/ 0 irb(main):016:0> a = "99999" "99999" irb(main):017:0> a =~ /^[+-]?\d+$/ 0 irb(main):014:0> a = "sldkfjer" "sldkfjer" irb(main):015:0> a =~ /^[+-]?\d+$/ nil Or, if you are not entirely fixed on using regular expressions you could also do this. You would do your Integer validation within a block that rescues the ArguementError exception. I prefer this one for integer validation because to me it is clearer. Thanks to matju in #ruby-talk for showing me this yesterday. irb(main):006:0> a = "99999" "99999" irb(main):007:0> Integer(a) 99999 irb(main):002:0> a = "+2343423" "+2343423" irb(main):003:0> Integer(a) 2343423 irb(main):004:0> a = "blarg" "blarg" irb(main):005:0> Integer(a) ArgumentError: invalid value for Integer: "blarg" from (irb):5:in `Integer' from (irb):5 Hope that helps. Have fun. - -- Signed, Holden Glova -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8KVXQ+mF116Lw2cQRAgdEAJ9iHqUenFBuT5wY+urcdb2+sgfiMQCeLL8Q M7hGxLn4oWxav9VdfJ22fe8= =D3Sc -----END PGP SIGNATURE-----