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

Question:

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.

Asked By: J.D. Marlin

||

Answers:

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
Answered By: black forest

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
Answered By: Sash Sinha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.