Siva
Siva

Reputation: 302

Perl regular expression to match numerics

Need to match BSC0 to BSC10 and "TOTAL". But the below condition is matching only BSC1 and BSC10. Whats missing? tried with s/regex/ m/regex/ variations also

$currentRowHeader will contain single word without spaces

if ($currentRowHeader =~ /BSC[0-10]|TOTAL/) { print "OK"}

Upvotes: 0

Views: 78

Answers (2)

Bohemian
Bohemian

Reputation: 424983

The dash in a character class is a range of characters, not values. Try this:

if ($currentRowHeader =~ /BSC(10|\d)|TOTAL/) 

FYI \d means "any digit" and is identical (with Latin characters) to coding [0-9], but shorter and easier to read.

As some pedants will tell you, \d includes non-Latin numbers like Arabic and Chinese symbols for numbers, but that is clearly irrelevant in the context of this question.

Upvotes: 2

Martin Ender
Martin Ender

Reputation: 44259

[...] is a character class. It can match only a single character. Regular expressions have no concepts of numbers - only of digit characters. What your regex is saying is

Match a character from 0 to 1 (that is 0 or 1) or match a 0.

So it only matches one binary digit. You could use

if ($currentRowHeader =~ /BSC(?:[0-9]|10)|TOTAL/) { print "OK" }

Note that the ?: is not necessary but is a good habit, as it suppresses unnecessary capturing and hence speeds up the operation.

Upvotes: 8

Related Questions