[Tutor] Regex not working as desired

Terry Carroll carroll at tjc.com
Mon Feb 26 20:16:59 EST 2018


On Mon, 26 Feb 2018, Roger Lea Scherer wrote:

> """ ensure input is no other characters than digits
> sudocode: if the input has anything other than digits
> return digits  """
  ....
> p = re.compile(r'[^\D]')

I'm not so great at regular expressions, but this regex appears to be 
searching for a string that matches anything in the class start-of-string 
of non-digit.

  "[...]" says, look for anything in this set of characters; and you have 
two things:
  ^ : start-of-string
  \D : any non-digit

Instead of looking fo re xcaprions, I would look for what you *do* want. 
this regex should do it for you:

   r'^\d+$'

This is looking for a start-of-string ("^"); then a digit ("\d") that 
occurs at least once (the "+" qualifier); then an end-of string ("$").

In other words, one or more digits, with nothing else before or after.

Here's a simple looping test to get you started (ignore the "from 
__future__" line; I'm running Python 2):

from __future__ import print_function
import re
p = re.compile(r'^\d+$')
test_data = ["4jkk33", "4k33", "4jjk4", "4334", "4","44", "444", ""]
for thing in test_data:
     m = p.match(thing)
     if m is None:
         print("not all digits:", thing)
     else:
         print("all digits:", thing)


-- 
Terry Carroll
carroll at tjc.com



More information about the Tutor mailing list