-2

Im trying to limit an input of phone numbers to:

  • 1-16 digits OR
  • A single "+" followed by 1-16 digits.

This is my code

txt = "+++854"
x = re.search(str("([\+]{0,1}[0-9]{3,16})|([0-9]{3,16})"), txt)



###^\+[0-9]{1,16}|[0-9]{1,16}", txt) #startswith +, followed by numbers.

if x:
  print("YES! We have a match!")
else:
  print("No match")

# Thatas a match

Yet it yields a match. I tried also "^+{0,1}[0-9]{1,16}|[0-9]{1,16}" but despite it works in "https://regex101.com/r/aP0qH2/4" it doesnt work in my code as i think it should work.

Galpaccru
  • 57
  • 12
  • 1
    `"(\+?[0-9]{1,16})"` should work as the regex expression, together with `re.match` as described by @ForceBrue. – Alexander Oct 13 '20 at 16:26

2 Answers2

2

re.search searches for "the first location where the regular expression pattern produces a match" and returns the resulting match object. In the string "+++854", the substring "+854" matches.

To match the whole string, use re.match. The documentation has a section about the difference between re.match and re.search.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 3
    "To match the whole string", well, almost. `re.match` matches at the beginning of the string, not necessarily the whole string. – L3viathan Oct 13 '20 at 16:24
  • 1
    @L3viathan, right - to match _the whole whole_ string, `^` and `$` should be used in the regex, but with this regex and this input it should be fine to just use `re.match` – ForceBru Oct 13 '20 at 16:27
0
pattern = r"\+?[0-9]{16}"
Al Mahdi
  • 635
  • 1
  • 9
  • 16
  • Its interesting that this also allows "+8+9875" per example. Im going with ([\+]{0,1}[0-9]{3,16})|([0-9]{1,16}) – Galpaccru Oct 15 '20 at 06:48