python - Look for files not having a given extension -
i'v tried following code.
import re regobj = re.compile(r"^.+\.(oth|xyz)$") test in ["text.txt", "other.oth", "abc.xyz"]: if regobj.match(test): print("method 1:", test) regobj = re.compile(r"^.+\.[^txt]$") test in ["text.txt", "other.oth", "abc.xyz"]: if regobj.match(test): print("method 2:", test)
i 2nd method finds file not having extension txt
way try not one. doing wrong ?
regular expressions overkill here. use str.endswith()
method:
if not str.endswith('.txt'):
your regular expression uses negative character class, set of characters should not matched. not t
or x
satisfy test. have explicitly matched .txt
, used not
exclude rather include:
regobj = re.compile(r"^.+\.txt$") if not regobj.match(test):
if can use regular expressions, use negative look-ahead assertions;
regobj = re.compile(r"^[^.]+\.(?!txt$)[^.]+$")
here (?!...)
matches locations there no literal txt
following, way end of string. [^.]+
matches number of characters not .
character until end of string.
Comments
Post a Comment