Regular Expression – To match a character n number of times [duplicate]

  • A+
Category:Languages

This question already has an answer here:

Problem
Regular expression in python that matches the a string where ‘a’ is followed by ‘b’ a maximum of three times.

Should match the following

a ab abb abbb 

Should not match the following

abbbb abbbbbbbb 

What I came up with:

ab{1,3} 

With this all the positive cases match (ie a ab abb abbb)
But abbbb abbbbb also matches with this which I do not want.

How do we model a n number of occurrence of a character in a string using regular expression?

 


The regex is already correct but you are using the wrong function to perform the match. You want to use re.fullmatch which is provided in python3.4+:

>>> import re >>> re.fullmatch(r'ab{1,3}', 'abbb') <_sre.SRE_Match object; span=(0, 4), match='abbb'> >>> re.fullmatch(r'ab{1,3}', 'abbbb') >>> # no output = no match 

The re.match function instead only checks it the text begins matching the given regex.

You can achieve the same behaviour with re.match by using the following anchors:

/Aab{1,3}/Z 

The /A only matches at the beginning of the string and /Z only at the end of the string (re.MULTILINE does not affect their behaviour).

This is different than just adding ^ and $ anchors:

>>> re.match(r'ab{1,3}', 'abbb/n') <_sre.SRE_Match object; span=(0, 4), match='abbb'> >>> re.fullmatch(r'ab{1,3}', 'abbb/n') >>> 

$ does not simply match at the end of text but also before the last /n! And their behaviour changes with re.MULTILINE.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: