How can I find out if a string contains ONLY digits and spaces in python using regex

I am trying to write some script in python (using regex) and I have the following problem:

I need to make sure that the string contains ONLY digits and spaces, but can contain any number of numbers.

The value must correspond to the lines: "213" (one number), "123 432" (two numbers) and even "123 432 543 3 235 34 56 456 456 234 324 24" (twelve numbers).

I tried searching here, but all I found was how to extract numbers from strings (and vice versa) - and this does not help me guarantee that ALL OF THE STRING weather contains ONLY digits (separated by any number of spaces).

Anyone have a solution?

If someone knows a class that contains all special characters (such as! $ # _ -), that would be great (because then I could just do [^ AZ] [^ az] [^ special class] and therefore get something that doesn't match any characters and special characters, leaving me with only numbers and spaces (if I'm right).

+4
source share
3 answers

The main regex will be

/^[0-9 ]+$/

However, it also works if your line contains only a space. To check for at least one number, you need the following

/^ *[0-9][0-9 ]*$/

You can try it on there

+2
source

This code checks to see if the string contains only numbers and a space.

if re.match("^[0-9 ]+$", myString):
    print "Only numbers and Spaces"
+8

, -, regex:

>>> s = "12a 123"
>>> to_my_linking = lambda x: all(var.isdigit() for var in x.split())
>>> to_my_linking(s)
False
>>> s = "1244 432"
>>> to_my_linking(s)
True
>>> a = "123 432 543 3 235 34 56 456 456 234 324 24"
>>> to_my_linking(a)
True

In case you work, lambdathis is just an easy way to make one liner function. If we wrote it using def, it will look like this:

>>> def to_my_linking(number_sequence):
...     return all(var.isdigit() for var in number_sequence.split())
...     
0
source

All Articles