I need to write func to check str. If should fit next conditions:
1) str should starts with alphabet - ^[a-zA-Z]
2) str may contains alphabet, numbers, one . and one -
3) str should ends with alphabet or number
4) length of str should be from 1 to 50
def check_login(str):
flag = False
if match(r'^[a-zA-Z][a-zA-Z0-9.-]{1,50}[a-zA-Z0-9]$', str):
flag = True
return flag
But it should mean that it starts with alphabet, length of [a-zA-Z0-9.-] is more than 0 and less 51 and it ends with [a-zA-Z0-9].
How can I limit quantity of . and - and write length's limit to all expression?
I mean that a - should returns true, qwe123 also true.
How can I fix that?
You will need lookaheads:
^ # start of string
(?=^[^.]*\.?[^.]*$) # not a dot, 0+ times, a dot eventually, not a dot
(?=^[^-]*-?[^-]*$) # same with dash
(?=.*[A-Za-z0-9]$) # [A-Za-z0-9] in the end
[A-Za-z][-.A-Za-z0-9]{,49}
$
See a demo on regex101.com.
Which in Python might be:
import re
rx = re.compile(r'''
^ # start of string
(?=^[^.]*\.?[^.]*$) # not a dot, 0+ times, a dot eventually, not a dot
(?=^[^-]*-?[^-]*$) # same with dash
(?=.*[A-Za-z0-9]$) # [A-Za-z0-9] in the end
[A-Za-z][-.A-Za-z0-9]{,49}
$
''', re.VERBOSE)
strings = ['qwe123', 'qwe-123', 'qwe.123', 'qwe-.-123', '123-']
def check_login(string):
if rx.search(string):
return True
return False
for string in strings:
print("String: {}, Result: {}".format(string, check_login(string)))
This yields:
String: qwe123, Result: True
String: qwe-123, Result: True
String: qwe.123, Result: True
String: qwe-.-123, Result: False
String: 123-, Result: False
Related
I have a bunch of string look like aaa -bx or aaa -bxx where x would be a digit. Is there any way to mach bx or bxx without using regrex? I remember there is something like b_ to match it.
You can use string methods.
Matching literal aaa -b followed by digits:
def match(s):
start = 'aaa -b'
return s.startswith(start) and s[len(start):].isdigit()
match('aaa -b33')
# True
If you rather want to check if the part after the last b are digits, use s.rsplit('b')[-1].isdigit()
Well it is not eloquent, but you can certainly test the string 'bxx' where xx represents one or two digits, manually, in a manner of speaking.
Here is an example. First check if it has sufficient length and starts with 'b'. Then check whether the next part is an integer.
def matchfunction(s):
if len(s) < 2 or s[0] != 'b':
return False
try:
int(s[1:])
return True
except:
return False
print( matchfunction( 'b23' ) )
print( matchfunction( 'bavb' ) )
The output, as expected, is
True
False
I have to validate that the string is either 4 or 6 digits. The string cannot contain any characters, only integers. Return true if it meets the condition else false.
I tried to create a list with acceptable digits and loop through the string and compare. If any part of the string is not in the acceptable list I will exit the loop and return false. If the running total is equal to 4 or 6 then it should be true.
python code:
def validate(n):
count = 0
valid_list = list(range(10))
for digit in pin:
if digit not in valid_list:
return False
count += 1
I'm not sure why something like 1234 is being returned as False.
How about with regex?
import re
str="03506"
pattern="[0-9]{4,6}"
prog=re.compile(pattern)
result=prog.match(str)
if result:
return True
else:
return False
This matches digits that are between 4 and 6 characters long. If you mean you want to match those string that are 4 or 6 long, you can try
import re
str="03506"
pattern1="[0-9]{4}"
pattern2="[0-9]{6}"
if re.match(pattern1,str) or re.match(pattern2, str):
return True
else:
return False
I'm not sure why something like 1234 is being returned as False.
Python never implicitly converts between integers and strings and comparisons between integers and strings are always false.
"valid_list" is a list of integers, but "digit" is a string, so you will never find anything in your list.
I need to write func to check str.
If should fit next conditions:
1) str should starts with alphabet - ^[a-zA-Z]
2) str should contains alphabet, numbers, . and - ([\w]+*.-)
3) str should ends with alphabet or number - \w$
4) length of str should be from 10 to 50
def check_login(str):
flag = False
if match(r'^[a-zA-Z]([\w]*.-)\w${10, 50}', str):
flag = True
return flag
It returns False to all combinations.
I think, error in 2 condition. I know, that I can use [a-zA-Z0-9\.-]+, but it does not indicate a mandatory entry.
How can I fix that?
Use:
match(r'^[a-zA-Z][\w.-]{8,48}\w$', str)
If you don't want to match _:
match(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', str)
If you want at least one dit, one dash, one letter and one digit:
^[a-zA-Z](?=.*-)(?=.*\.)(?=.*[0-9])[a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$
Where (?=....) is a lookahead, a zero-length assertion, that makes sure we have its content in the string.
Straight-forward approach with re.search() function:
import re
def check_login(s):
return bool(re.search(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', s)
and re.search(r'\.[a-zA-Z0-9]*-|-[a-zA-Z0-9]*\.', s[1:-1]))
# test cases
print(check_login('al-De.5af3asd.2')) # True
print(check_login('3lDe.5af3asd.2')) # False
print(check_login('al-De.5a')) # False
print(check_login('xl-De.5a3333333333333')) # True
You can try this regex:
import re
final_string = [''] if not re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s) else re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s)
if final_string[0] == s:
#success, a match has been found.
pass
So a user will input a string value in binary format. i.e. '01000001'
I want to check the value they enter to see if it:
has only eight characters.
is a string type
and only contains '0's or '1's
preferably to be done with a function that takes in the user value so that i can call it whenever. Returns false if conditions are not met.
this is what i came up with so far...
size = len(teststring)
teststring = '11111111'
def typecheck(value):
if type(user_input) == type(teststring) and len(user_input) == size and contains only 1 | 0
return
You can use regex matching here:
reg = re.compile(r'^[01]{8}$')
def typecheck(value):
return isinstance(value, str) and bool(reg.match(value))
Or since you want to check for binary format number, how about converting it to int with base 2, and see if it's a valid conversion:
def typecheck(value):
try:
return len(value) == 8 and bool(int(value, 2))
except TypeError, ValueError:
return False
No need for regex
You could use str.strip() and strip all 1 and 0 from end and beginning and check.
Code:
check = "11101110"
if isinstance(check,str) and len(check)==8 and check.strip("01")=='':
print "yes"
Output:
yes
This can be done with one if statement. If the regex doesn't find a match it will return None which evaluates to False in a truth test.
import re
def check_input(user_input):
if not re.match(r'^[01]{8}$', user_input):
it doesn't meet requirements do something
This is my code. it seems to be checking only the first character. I'd like to know how to fix it.
import string
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DECIMAL_DIGITS = "0123456789"
ALPHABETS = ASCII_LOWERCASE + ASCII_UPPERCASE
def is_alpha(string):
for c in "string":
if c in ALPHABETS:
return False
else:
return True
Do not return in every iteration, only return False when you find something that is not in ALPHABET. What about this?
def is_alpha(your_string):
for c in your_string:
if c not in ALPHABETS:
return False
return True
actually its almost half right:
def is_alpha(string):
for c in string:
if not c in ALPHABETS:
return False
return True
short circuiting on False is ok but you need to finish the loop to determine True
There's several issues with your code here.
In your function definition you say
for c in "string"
which means you're checking the characters in the string literal "string".
You'll need to remove the quotes to have it refer to your parameter and actually check the string you're looking at. Further, you should change the name of your parameter and variable to something less ambiguous than string.
As Two-Bit Alchemist points out, you're returning from inside the loop so if the first character is in ALPHABETS then it returns and doesn't execute any more.
Which goes to the final issue. You're returning False if it is an alpha character instead of true. If you change
if c in ALPHABETS:
return False
to
if c not in ALPHABETS:
return False
then delete the else branch and put the return True after the loop it will work as you intend.
Change your function like this:
def is_alpha(string):
for c in string:
if c not in ALPHABETS:
return False
return True
First of all, you had for c in "string": in your code. There you are creating a new string ("string") and looping through the characters in it. Instead, you want to loop through the parameter passed to your function. So remove the double quotes.
Your function returns after first character because you are returning in both cases. Return true only when all characters are in ALPHABETS