当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Regular expression for repeating sequence

问题描述:

I'd like to match three-character sequences of letters (only letters 'a', 'b', 'c' are allowed) separated by comma (last group is not ended with comma).

Examples:

abc,bca,cbb

ccc,abc,aab,baa

bcb

I have written following regular expression:

re.match('([abc][abc][abc],)+', "abc,defx,df")

However it doesn't work correctly, because for above example:

>>> print bool(re.match('([abc][abc][abc],)+', "abc,defx,df")) # defx in second group

True

>>> print bool(re.match('([abc][abc][abc],)+', "axc,defx,df")) # 'x' in first group

False

It seems only to check first group of three letters but it ignores the rest. How to write this regular expression correctly?

网友答案:

Try following regex:

^[abc]{3}(,[abc]{3})*$

^...$ from the start till the end of the string
[...] one of the given character
...{3} three time of the phrase before
(...)* 0 till n times of the characters in the brackets

网友答案:

What you're asking it to find with your regex is "at least one triple of letters a, b, c" - that's what "+" gives you. Whatever follows after that doesn't really matter to the regex. You might want to include "$", which means "end of the line", to be sure that the line must all consist of allowed triples. However in the current form your regex would also demand that the last triple ends in a comma, so you should explicitly code that it's not so. Try this:

re.match('([abc][abc][abc],)*([abc][abc][abc])$'

This finds any number of allowed triples followed by a comma (maybe zero), then a triple without a comma, then the end of the line.

Edit: including the "^" (start of string) symbol is not necessary, because the match method already checks for a match only at the beginning of the string.

网友答案:

You need to iterate over sequence of found values.

data_string = "abc,bca,df"

imatch = re.finditer(r'(?P<value>[abc]{3})(,|$)', data_string)

for match in imatch:
    print match.group('value')

So the regex to check if the string matches pattern will be

data_string = "abc,bca,df"

match = re.match(r'^([abc]{3}(,|$))+', data_string)

if match:
    print "data string is correct"
网友答案:

Your result is not surprising since the regular expression

([abc][abc][abc],)+

tries to match a string containing three characters of [abc] followed by a comma one ore more times anywhere in the string. So the most important part is to make sure that there is nothing more in the string - as scessor suggests with adding ^ (start of string) and $ (end of string) to the regular expression.

网友答案:

An alternative without using regex (albeit a brute force way):

>>> def matcher(x):
        total = ["".join(p) for p in itertools.product(('a','b','c'),repeat=3)]
            for i in x.split(','):
                if i not in total:
                    return False
         return True

>>> matcher("abc,bca,aaa")
    True
>>> matcher("abc,bca,xyz")
    False
>>> matcher("abc,aaa,bb")
    False
网友答案:

If your aim is to validate a string as being composed of triplet of letters a,b,and c:

for ss in ("abc,bbc,abb,baa,bbb",
           "acc",
           "abc,bbc,abb,bXa,bbb",
           "abc,bbc,ab,baa,bbb"):
    print ss,'   ',bool(re.match('([abc]{3},?)+\Z',ss))

result

abc,bbc,abb,baa,bbb     True
acc     True
abc,bbc,abb,bXa,bbb     False
abc,bbc,ab,baa,bbb     False

\Z means: the end of the string. Its presence obliges the match to be until the very end of the string

By the way, I like the form of Sonya too, in a way it is clearer:

bool(re.match('([abc]{3},)*[abc]{3}\Z',ss))
网友答案:

The obligatory "you don't need a regex" solution:

all(letter in 'abc,' for letter in data) and all(len(item) == 3 for item in data.split(','))
分享给朋友:
您可能感兴趣的文章:
随机阅读: