Home > other >  How to return true if string does not contain certain characters?
How to return true if string does not contain certain characters?

Time:10-27

I'm trying to get re.match(...) to return true if a string does not contain: , -, *, or / (plus, minus, multiply, divide).

Example ABC-DEF or XYZ/3 should return false.

I've tried [^ -*/] but it keeps picking up ABC or XYZ.

CodePudding user response:

Consider utilizing re.search and escaping the minus and exponent symbols:

import re


def does_not_contain_math_symbol(s: str) -> bool:
    return re.search(r'[ \-*/\^]', s) is None


def main() -> None:
    print(f'{does_not_contain_math_symbol("ABC*DEF") = }')
    print(f'{does_not_contain_math_symbol("XYZ/3") = }')
    print(f'{does_not_contain_math_symbol("ABC DEF") = }')
    print(f'{does_not_contain_math_symbol("XYZ-3") = }')
    print(f'{does_not_contain_math_symbol("ABC^DEF") = }')
    print(f'{does_not_contain_math_symbol("ABC or XYZ") = }')


if __name__ == '__main__':
    main()

Output:

does_not_contain_math_symbol("ABC*DEF") = False
does_not_contain_math_symbol("XYZ/3") = False
does_not_contain_math_symbol("ABC DEF") = False
does_not_contain_math_symbol("XYZ-3") = False
does_not_contain_math_symbol("ABC^DEF") = False
does_not_contain_math_symbol("ABC or XYZ") = True

CodePudding user response:

i Don't undrtand verry well ur question but this may help u .#sorry for my English

import re


def is_math(string):
    if re.search(r'[\ \-\*\/]', string):
        return False
    return True

print(is_math('ab cd')) # print -> False
print(is_math('abcd')) # print -> True
  • Related