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.
CodePudding user response:
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()
CodePudding user response:
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