Basque0407 Basque0407 - 27 days ago 7
Perl Question

Regular Expression for getting single digits

I have this sample data:

1
2a
12
23a


Using regular expressions, I would like to substitute data with single digits into this format:

01
02a
12
23a


Any other suggestions would be a big help as well

Answer

You could use this regex with multiline m flag:

(?<!\d)(\d)(?=[a-zA-Z]|$)

Then replace with 0\1.

my $str = 'your data'
my $regex = qr/(?<!\d)(\d)(?=[a-zA-Z]|$)/mp;
my $subst = '0\\1';
my $result = $str =~ s/$regex/$subst/rg;
  • (?<!\d) is a negative lookbehind. Match will start only if previous character is not a digit
  • (\d) is the first group, it matches one digit
  • (?=[a-zA-Z]|$) ends match if next character is a letter ([a-zA-Z]) or line ends has been reached ($)
  • Substitute 0\1 is the first group (the digit) preceded by zero