简体   繁体   中英

check for string to be list of integers separated by + signs in python

I want to check that myvar to be one or more integers separated by + signs . Should this re.search() be enough?

myvar = "1+2+3"
if (re.search(r"^[0-9]+(\+[0-9]+)*$", myvar)):
    print "myvar should be + separated integers (%s)" % myvar
     sys.exit(1)

Then I realised that this will still work for incorrect cases like:

myvar = "1+2+3-4"

myvar should be + separated integers

Take this input:

$ cat in.txt 
1+2+3+4
1+2
foo 1+2 bar
foo 1+2
1+2 bar
1
+

Four of these lines contain only '+ separated integers':

$ grep -E '^[0-9]+(\+[0-9]+)*$' < in.txt 
1+2+3+4
1+2
1

So you initial regexp does not what you want it to do.

You can use this regexp in Python, too.

Edit

import re

with open("in.txt") as i:
    for line in i:
        m = re.search(r"^[0-9]+(\+[0-9]+)*$", line.strip())
        if m:
            print(line.strip() + " matches")

Output:

$ python match.py                                                                 :(
1+2+3+4 matches
1+2 matches
1 matches

A regex free alternative is to use split:

myvars = ["+1", "1++2", "1+5", "1+2+3"]
for myvar in myvars:
    nums = myvar.split('+')
    for num in nums:
        try: int(num)
        except: print "error", myvar

Gives:

error +1
error 1++2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM