DrFalk3n
DrFalk3n

Reputation: 5006

Python regular expression to match # followed by 0-7 followed by ##

I would like to intercept string starting with \*#\*

followed by a number between 0 and 7

and ending with: ##

so something like \*#\*0##

but I could not find a regex for this

Upvotes: 2

Views: 506

Answers (5)

tzot
tzot

Reputation: 95971

As I understand the question, the simplest regular expression you need is:

rex= re.compile(r'^\*#\*([0-7])##$')

The {1} constructs are redundant. After doing rex.match (or rex.search, but it's not necessary here), .group(1) of the match object contains the digit given.

EDIT: The whole matched string is always available as match.group(0). If all you need is the complete string, drop any parentheses in the regular expression:

rex= re.compile(r'^\*#\*[0-7]##$')

Upvotes: 1

doomspork
doomspork

Reputation: 2342

None of the above examples are taking into account the *#*

^\*#\*[0-7]##$

Pass : *#*7##

Fail : *#*22324324##

Fail : *#3232#

The ^ character will match the start of the string, \* will match a single asterisk, the # characters do not need to be escape in this example, and finally the [0-7] will only match a single character between 0 and 7.

Upvotes: 4

Mark Biek
Mark Biek

Reputation: 150799

Assuming you want to allow only one # before and two after, I'd do it like this:

r'^(\#{1}([0-7])\#{2})'

It's important to note that Alex's regex will also match things like

###7######
########1###

which may or may not matter.

My regex above matches a string starting with #[0-7]## and ignores the end of the string. You could tack a $ onto the end if you wanted it to match only if that's the entire line.

The first backreference gives you the entire #<number>## string and the second backreference gives you the number inside the #.

Upvotes: 7

Blindy
Blindy

Reputation: 67386

The regular expression should be like ^#[0-7]##$

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881863

r'\#[0-7]\#\#'

Upvotes: 1

Related Questions