Search code examples
pythonstringmatchstring-matching

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

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