Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex 1

Status
Not open for further replies.

BigBadDave

Programmer
May 31, 2001
1,069
EU
Ho do I only match these chars: [a-z][A-Z][0-9] Regards
David Byng
bd_logo.gif

davidbyng@hotmail.com
 
So I use:

my $str = "Hello£$^";

if ($str =~ /[_A-Za-z0-9]/) {
print "String OK!";
} else {
print "Bad string!";
}

But that still allows any other chars eg: '£$^'

How do I stop them? Regards
David Byng
bd_logo.gif

davidbyng@hotmail.com
 
You'd say:

[tt]if ($str =~ /^[_A-Za-z0-9]*$/) {
print "String OK";
} else {
print "String bad";
}
[/tt]

The [tt]^[/tt] matches the start of the string, the [tt]$[/tt] matches the end of the string. The [tt]*[/tt] after the character class matching the characters you're allowing matches 0 or more -- as many as possible.

Note that this would allow the string "" to match. If you didn't want that, replace the [tt]*[/tt] with a [tt]+[/tt], which says to match one or more.

Since you're allowing [tt]_[/tt] as well as the characters asked about, by the way, you can use the predefined character class \w ...
[tt]if ($str =~ /^\w*$/) {[/tt]
 
Hi thanks but now it won't allow any string, this is what i've got:

Code:
sub Legal {
    my $str = $_[0];
    if ($str =~ /^[_A-Za-z0-9]+$/) {
        return 1;
    }
    return 0;
} # Legal chars
Regards
David Byng
bd_logo.gif

davidbyng@hotmail.com
 
What string are you passing in? That code works perfectly for me.
 
This:

Code:
if (Legal ("hello_world")) {
    print "Legal string";
}

sub Legal {
    my $str = $_[0];
    if ($str =~ /^[_A-Za-z0-9]+$/) {
        return 1;
    }
    return 0;
} # Legal chars

Nothing is printed even though it is a legal string Regards
David Byng
bd_logo.gif

davidbyng@hotmail.com
 
That's very strange. Cutting and pasting that exact code works for me.
 
[tt]sub Legal {
return $_[0] =~ /^\w*$/;
}[/tt]

is a direct equivalent if you only want a boolean return value. BigBadDave's code works fine on my system as well.

"As soon as we started programming, we found to our surprise that it wasn't as
easy to get programs right as we had thought. Debugging had to be discovered.
I can remember the exact instant when I realized that a large part of my life
from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilk
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top