WindedHero
WindedHero

Reputation:

Perl regex: Numbers and X

How to strip a string of everything but numbers and the letter x (if it exists) with regex in Perl?

2x4 works
x3405 does not work
2 works

Trying to do the top rated answer but I have no idea.

This as far as I can get without screwing it up:

$string =~ s/[\D]//gi;

Or am I headed in the wrong direction?

A comprehensive regex for phone number validation

Upvotes: 2

Views: 307

Answers (4)

DavidO
DavidO

Reputation: 13942

Are you concerned with the possibility of people using 'spelled numbers'? (eg, 1-800-FLOWERS translates to 1-800-356-9377). And if that is a possibility, how do you distinguish between 'X' (9), or 'x' (extension)? I'm not sure what your context is, but you may wish to not only silently drop alpha characters, you may wish to issue a warning that alpha based phone numbers aren't permitted.

That complexity aside, there are a few CPAN modules that might prove helpful rather than rolling your own phone number validator:

Upvotes: 2

Alnitak
Alnitak

Reputation: 339786

The tr operator can be used to remove characters:

$string =~ tr/0-9x//cd;

Where the c flag indicates "match the opposite" and the d flag means "delete".

NB: the transliteration operator is also available as y/// but is aliased tr too after the UNIX command line utility that does a similar job.

Upvotes: 7

ysth
ysth

Reputation: 98388

Use the transliteration operator:

$string =~ y/0-9x//cd;

Note that in this brave new unicode world, \D and \d mean more than just 0-9, and 0-9 is probably what's wanted here.

Upvotes: 5

Mathieu Rodic
Mathieu Rodic

Reputation: 6762

You could use the following code:

$string =~ s/[^\dx]//gi;

Upvotes: 1

Related Questions