Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match one or more digits

Tags:

python

regex

I got dataset like that (it's opened as str from file):

MF8='out1mf8':'constant',[1944.37578865883]
MF9='out1mf9':'constant',[2147.79853787502]
MF10='out1mf10':'constant',[565.635908155949]
MF11='out1mf11':'constant',[0]
MF12='out1mf12':'constant',[0]

I need this values in brackets, so a created regex:

outmfPattern = 'out\dmf\d'

and used:

re.findall(outmfPattern, f)

It's working nice until mf = 9. Does anybody has idea how to handle with this?

like image 418
Iks Avatar asked Dec 11 '25 17:12

Iks


1 Answers

Let's break down your regex out\dmf\d:

  • out matches the sequence 'out'
  • \d matches a digit
  • mf match the sequence 'mf'
  • \d matches a digit

If you want to match something like out1mf11, you'll need to look for 2 digits at the end.

You can use out\dmf\d+, or, if you want to match only 1 or 2 digits at the end, out\dmf\d{1,2}.


In [373]: re.findall('out\dmf\d+', text)
Out[373]: ['out1mf8', 'out1mf9', 'out1mf10', 'out1mf11', 'out1mf12']

Furthermore, if you want to add brackets to those search items, you probably should look at re.sub instead:

In [377]: re.sub('(out\dmf\d+)', r'(\1)', text)
Out[377]: "MF8='(out1mf8)':'constant',[1944.37578865883] MF9='(out1mf9)':'constant',[2147.79853787502] MF10='(out1mf10)':'constant',[565.635908155949] MF11='(out1mf11)':'constant',[0] MF12='(out1mf12)':'constant',[0]"

re.sub replaces the captured groups with the same enclosed in parens.

like image 149
cs95 Avatar answered Dec 13 '25 07:12

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!