How to Find Words Not Containing Specific Letters?

I’m trying to write a code using regex and my text file. My file contains these words line by line:

nana
abab
nanac
eded

My purpose is; displaying the words which are not contain the letters which are given a substring’s letters.

For example, if my substring is “bn”, my output should be only eded. Because nana and nanac contains “n” and abab contains “b”.

I have written a code but it only checks first letter of my substring.

import re
substring = "bn"
def xstring():
    with open("deneme.txt") as f:
        for line in f:
            for word in re.findall(r'\w+', line):
                for letter in substring:
                    if len(re.findall(letter, word)) == 0:
                        print(word)
                        #yield word
xstring()

How do I solve this problem?

Solution:

If you want to check if a string has a set of letters, use brackets.
For example using [bn] will match words that contain one of those letters.

import re
substring = "bn"
regex = re.compile('[' + substring + ']')
def xstring():
    with open("dename.txt") as f:
        for line in f:
            if(re.search(regex, line) is None):
                print(line)
xstring()

In Python, should a regex pattern always start with ^ and end with $?

I have noticed that most regex patterns start with ^ and end with $. However, if these identifiers are not provided, the pattern still works like it is supposed to most of the time. So my question is, is this just a good practice to make sure that this is always the case?

The reason I ask is I am building a regex tester website using Django where users can store their regex objects, and then test them out. If this is always a good idea, I would write a function which takes in the user input pattern and make sure it starts with ^ and ends with $. Something like this:

 def standardize_pattern(self):
    pattern = self.pattern
    if len(self.pattern) > 0:
        if not self.pattern[0] == '^':
            pattern = '^' + pattern
        if not self.pattern[-1] == '$':
            pattern = pattern + '$'
    else:
        pattern = '^$'
    self.pattern = pattern

Any explanation is appreciated.

Solution:

No, start and end anchors may not be about a good practice. Sometimes they might be required, sometimes might be unnecessary, sometimes is just good to add for ensuring additional constraints to just have a more safe expression, especially if the expression is for validation purposes.

If we wish to capture or search things in string, usually we do not use them.

For your goal, it seems to be necessary.