Help with regex search

I dont know where to put this so i am putting it here sorry if its wrong but my code is this:

 Answer = input("Hello "+Human+" I am "+Bot+ "How are you today?")
        HumanEmotion = 0
        import re
        with open ("Feelings.txt", "a") as myfile:
            result = re.search("?",Answer)
            if result != nill:
                myfile.close()
            if result == nill or "None":
                myfile.write(Answer+"\n")
                myfile.close()

and the output is

Hello Dave I am Zelda
How are you today?good?
Traceback (most recent call last):
  File "D:\1Bot\Startup.py", line 54, in <module>
    result = re.search("?",Answer)
  File "D:\lib\re.py", line 201, in search
    return _compile(pattern, flags).search(string)
  File "D:\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)
  File "D:\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "D:\lib\sre_parse.py", line 948, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
  File "D:\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,
  File "D:\lib\sre_parse.py", line 668, in _parse
    raise source.error("nothing to repeat",
re.error: nothing to repeat at position 0

What have i done wrong?

Hi Bobbie,

is there any particular reason you’re trying to use the re module? Regular expressions are a powerful tool, but they’re also quite a complex language and often not the best tool for the job — depending on what you’re trying to do.

"?" is not a valid regular expression.

If you’re want to check if a certain character or substring is present in a string, the easiest way is to use the in operator:

>>> "?" in "no question marks here"
False
>>> "?" in "Is there a question mark?"
True

If you want to know where in a string a particular fixed substring can be found, str has a find method:

>>> "Where is the ? here".find("?")
13
>>> "Where is the ? here"[13]
'?'
>>> "no question mark here".find("?")
-1
>>> 
1 Like

Hi Bobbie,

“?” is not a valid regular expression. Regular expression (“regex”)
syntax is an extremely compressed, terse mini-programming language, and
your program “?” is buggy. What you tried to ask the regex engine to do
is match zero or one of nothing at all, which is impossible.

You can fix the regex by changing it to:

re.search(r"\?", Answer)

(notice the r is on the outside of the quotes) but that’s just a
confusing and expensive way of saying:

"?" in Answer

But it is hard to tell whether or not you should use the regex version
or not. Do you actually use it for anything?

You can also fix some other problems in your code. Get rid of all the

myfile.close()

lines, they are not needed when you have “with open(…)” as the “with”
statement will automatically close the file when you are done.

1 Like