Reputation: 65
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 (i.e.
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 (i.e. 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
Upvotes: 1
Views: 106
Reputation: 626845
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
).
Upvotes: 1