'Python how to match a character followed by anything without using regrex?

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.



Solution 1:[1]

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()

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2