• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 439
  • Last Modified:

match either whole alpha characters or whole numeric character but not alpha numeric characters

Hey,

I need some help in regular expressions in perl

I am trying to get an regular expression for accepting the whole numeric value or a whole alphabets but not alpha numeric  values.

for example: it should accept "3445" or "apple" but not "34dsd"

Thanks in Advance

 
0
sudarshan1985
Asked:
sudarshan1985
  • 2
1 Solution
 
ronnymaCommented:
\b[a-z]+\b|\b[0-9]+\b
0
 
marchentCommented:
if("123123" =~ /^([a-zA-Z]+|[0-9]+)$/){
    print "ok\n";
}
0
 
ronnymaCommented:
This regex requires that a matching expression is either a sequence of alpha-numeric characters og numerals preceded and succeded by a word boundary symbol, e.g. a space, punctuation mark etc.

\b[a-z]+\b|\b[0-9]+\b

Of course you would use the i-modifier in Perl to make it case insensitive.

my $testcase = "afFfd5";

if( $testcase =~ /\b[a-z]+\b|\b[0-9]+\b/i ) {
  print "Either numerals of characters exclusve\n";
 
}
else {
  print "A mix of characters and numbers\n";
}
0
 
Fero45Commented:
ronnyma's answer is complete. The author of the question probably need some guidance. He did not specify if the regex should be applied to a string or a text file.
For string, try using this .... for a text file, ask for further help :-)
#!/usr/bin/perl
use warnings;
use strict;

my $from_string = "123 gre45 apple 23 rum dr9";
my @to_array = split /\s/, $from_string;

foreach my $t ( @to_array )	{
	if($t =~ m/\b[a-z]+\b|\b[0-9]+\b/)	{
	print $t,"\n";
	}
}

# ======== out should be =============
123
apple
23
rum

# ====================================
I only copied ronnyma's regex and do not deserve any points. This is only to clarify things if the author of the question is a beginer.

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now