Welcome to the most active Linux Forum on the web.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 07-06-2004, 12:01 PM   #1
Registered: Jul 2002
Distribution: Slackware 10.0
Posts: 46

Rep: Reputation: 16
perl simple regexp

Hi....have a very simple reg exp, but I cant get it to work as I want.

my $digit = 12;

if ($digit =~ /\d/) {
  print ("match\n");
} else {
  print ("not match\n");

This prints match, although it should'nt cuz I have 2 digits. But if I change it to \d\d\d, it prints
not match. As it should. The point is that I want to match exactly 1 digit, not 1 or more.

Not sure whats wrong. Any ideas?
Old 07-06-2004, 01:21 PM   #2
LQ Guru
Registered: Mar 2004
Distribution: Slackware
Posts: 5,393

Rep: Reputation: 409Reputation: 409Reputation: 409Reputation: 409Reputation: 409
try if( $digit =~ /^\d$/ )
Old 07-06-2004, 01:28 PM   #3
Registered: Apr 2004
Location: Minneapolis
Distribution: Ubuntu
Posts: 45

Rep: Reputation: 15
There are many ways to solve this problem, all of which are covered in the Perl Regular Expressions documentation.

# match exactly one digit somewhere in string
$digit =~ m/\d{1}/;

# entire string must consist of one digit
$digit =~ m/^\d$/;

# match one digit with non-digits on either side
$digit =~ m/\D\d\D/;
Hope this helps,
-Adam Monsen
Old 07-07-2004, 04:27 AM   #4
Registered: Jul 2002
Distribution: Slackware 10.0
Posts: 46

Original Poster
Rep: Reputation: 16
thanks to both of you....I had to add the ^ and $, and it worked.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Perl Regexp search-n-replace jpbarto Programming 2 06-16-2005 01:45 PM
Perl/regexp help... - query string parsing... lowpro2k3 Programming 4 05-11-2005 06:18 PM
simple regex not so simple (perl) ludeKing Programming 5 03-02-2005 03:29 AM
perl regexp problem raven Programming 4 03-22-2004 12:49 AM
simple perl tunedLow Programming 4 06-04-2002 04:08 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:44 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration