Q:

Regex to check if it is exactly one single word

I am basically trying to match string pattern(wildcard match)
Please carefully look at this - 
*(star) - means exactly one word .
This is not a regex pattern...it is a convention.
So,if there patterns like - 
*.key - '.key.' is preceded by exactly one word(word containing no dots)
*.key.* - '.key.' is preceded and succeeded by exactly one word having no dots
key.* - '.key' preceeds exactly one word .

So,    
"door.key" matches "*.key"
"brown.door.key" doesn't match "*.key".
"brown.key.door" matches "*.key.*"
 but "brown.iron.key.door" doesn't match "*.key.*"

So, when I encounter a '*' in pattern, I have replace it with a regex so that it means it is exactly one word.(a-zA-z0-9_).Can anyone please help me do this in python?

A:

To convert your pattern to a regexp, you first need to make sure each character is interpreted literally and not as a special character. We can do that by inserting a \ in front of any re special character. Those characters can be obtained through sre_parse.SPECIAL_CHARS.
Since you have a special meaning for *, we do not want to escape that one but instead replace it by \w+.
Code
import sre_parse

def convert_to_regexp(pattern):
    special_characters = set(sre_parse.SPECIAL_CHARS)
    special_characters.remove('*')

    safe_pattern = ''.join(['\\' + c if c in special_characters else c for c in pattern ])

    return safe_pattern.replace('*', '\\w+')

Example
import re

pattern = '*.key'
r_pattern = convert_to_regexp(pattern) # '\\w+\\.key'

re.match(r_pattern, 'door.key') # Match
re.match(r_pattern, 'brown.door.key') # None

And here is an example with escaped special characters
pattern = '*.(key)'
r_pattern = convert_to_regexp(pattern) # '\\w+\\.\\(key\\)'

re.match(r_pattern, 'door.(key)') # Match
re.match(r_pattern, 'brown.door.(key)') # None

Sidenote
If you intend looking for the output pattern with re.search or re.findall, you might want to wrap the re pattern between \b boundary characters. 

