0

I would like to check if a string is of the following regex structure: [0-9]+-[0-9]+

I have the following Python code which, unfortunately, also returns a match when my input string includes the defined pattern and additional characters:

import re

my_string = '100-300'
re.match(r'[0-9]+-[0-9]+', my_string)    # returns a match as desired

my_string = 'abc100-300cyd'
re.match(r'[0-9]+-[0-9]+', my_string)    # also returns a match 

How can I extend my pattern matching so that I only get a match when the pattern is matched and no additional characters are present?

Dahlai
  • 695
  • 1
  • 4
  • 17

1 Answers1

3

Place a ^ for the beginning of a line and a $ for the end like

^[0-9]+-[0-9]+$

EDIT: As @Wiktor noticed, the full match of a complete line does not work on a complete string if it contains line breaks. So you would have to test for line breaks regardless of the programming language or use re.fullmatch.

TheSlater
  • 642
  • 1
  • 4
  • 11
  • No need for `^` and `$` that do not ensure full string match in Python. Try it in `re.search(r'^[0-9]+-[0-9]+$', '12-34\n')` and you will get a match. The right answer is "use `re.fullmatch`". – Wiktor Stribiżew Oct 24 '20 at 21:41