in reply to REGEX Match Single Digit

For all your regex-reference needs, check out perlre and perlretut. The pretty much cover the gamut.

If you know your digit ahead of time, there's not need to worry about character classes. You can just use:

/^1$/

if you are committed to using a regular expression. If you don't know until runtime, you can use

/^$value$/

where you have stored your value in the variable $value. You need to remember that regular expressions are just a fancy string matching engine, so don't think about numbers as numbers, but as characters.

However since you are not really performing flexible matches at this point but are checking equality, you should be using Equality Operators. For a string comparison, eq is the correct choice, but since you are checking numbers, you should use

if ($_ == 1) { # Do stuff }

Replies are listed 'Best First'.
Re^2: REGEX Match Single Digit
by spickles (Scribe) on Aug 28, 2009 at 16:00 UTC
    kennethk -

    *SLAPS forehead*
    That simple, eh? That will match just the number 1, and not 11, or 111, etc. Lemme try it out. Does that work if I read the number one from <STDIN> and chomp the newline? Is the digit 1 now string 1?

      That will match just the number 1, and not 11, or 111, etc.

      It matches "1" and "1\n" only.

      /^1$/:

      1. At the start of the input,
      2. match "1", then
      3. optionally match "\n", then
      4. match the end of the input string.

      /^1\z/ will only match "1".

      One of the things I love about Perl is the weak typing on scalars. The digit 1 and the string "1" have roughly equivalent internal representations and which one is used depends upon the context of your call. For example the line

      print "1 line of text" + 1;

      will output the string "2". You start with a string and a number combined with the + operator. That operator takes two numbers as arguments, so perl attempts to convert the string to a number - this truncates from the first non-numeric character. We then evaluate 1+1 = 2. That two is then passed to the print subroutine, which takes a string input. Therefore, 2 is converted to "2" and output to STDOUT. Coming from a strongly-typed background, that still fills me with a profound warmth every time I do it.