Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching optional numbers in regex

Tags:

python

regex

This one is probably a simple one, but I could not find an example that's simple enough to understand (sorry, I'm new with RegEx).

I'm writing some Python code to search for any string that matches any of the following examples:

float[20]
float[7532]
float[]

So this is what I have so far:

import re
p = re.compile('float\[[0-9]+\]')
print p.match("float[20]")
print p.match("float[7532]")
print p.match("float[]")

The code works great for the first and second scenarios, but not the third (no numbers between brackets). What's the best way to add that condition?

Thanks a lot!

like image 559
wotaskd Avatar asked Nov 19 '25 04:11

wotaskd


2 Answers

p = re.compile('float\[[0-9]*\]')

putting a * after the character class means 0 or matches of the character class.

like image 127
jon Avatar answered Nov 21 '25 16:11

jon


Try

float\[\d*\]

\d is a shortcut for [0-9]. The asterisk matches 0..n (any number) of characters of the character class.

like image 25
Markus Palme Avatar answered Nov 21 '25 17:11

Markus Palme



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!