简体   繁体   中英

Regex specific format with numbers separated with commas (in Python)

I am trying to check for specific format to be true and the function to return either 1 or 0 if the format is correct or incorrect. Format that I am trying to use would be numbers separated with commas and spaces (ie 0, 13, 24, 27 ). My current code works to some extent, but it does not detect that only one space is in front of a number and if I were to add some random text in the middle (ie 0, 13, 24asd, 27 ), it still detects this as a valid format. How should I go about fixing this?

Code:

def format_placement(string):
    is_correct = 0
    pattern = re.compile(r'(\d+)(?:,(\d+)*)')
    if re.findall(pattern, string):
        is_correct = 1
    return is_correct

You may use re.fullmatch to match the full string with the pattern, and add a space to the regex after a comma (or \s if you allow any whitespace):

def format_placement(string):
    is_correct = 0
    if re.fullmatch(r'\d+(?:, \d+)*', string):
        is_correct = 1
    return is_correct

See the regex demo ( ^ indicated the start of a string and $ marks the end of string, these anchors are not necessary when you use re.fullmatch ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM