Reputation: 1879
What will be the best regular expression if I want to intake alphanumerics, '-' and '+' signs. e.g. LA2+4 or td1-23
Upvotes: 0
Views: 114
Reputation: 15184
Do you want to parse any numerical representation?
Or just a few? In Perl (your language not given)
you could just use:
use Scalar::Util qw( looks_like_number )
my $stuff = get_weird_input();
...
if( looks_like_number($stuff) ) {
convert( ... )
}
...
Upvotes: 0
Reputation: 172200
No magic involved, just specify that your complete string (^...$
) must match a sequence of arbitrary length (...*
) of alternatively ([...]
) upper-case letters (A-Z
), lower-case letters (a-z
), digits (0-9
), the plus sign (+
) and the minus sign (-
).
The only special case to consider is the fact that the minus sign you want to accept (-
) must appear as the last (or first) letter in the option group, since the same character is also used to specify ranges (as in A-Z
).
So, the solution is:
^[A-Za-z0-9+-]*$
Upvotes: 2