title: How to save a regular expression user input value (Python)
body: <p>I am making a simple chat bot in Python. It has a text file with regular expressions which help to generate the output. The user input and the bot output are separated by a <code>|</code> character. </p>
  
  <pre><code>my name is (?P&lt;'name'&gt;\w*) | Hi {'name'}!
  </code></pre>
  
  <p>This works fine for single sets of input and output responses, however I would like the bot to be able to store the regex values the user inputs and then use them again (i.e. give the bot a 'memory'). For example, I would like to have the bot store the value input for 'name', so that I can have this in the rules:</p>
  
  <pre><code>my name is (?P&lt;'word'&gt;\w*) | You said your name is {'name'} already!
  my name is (?P&lt;'name'&gt;\w*) | Hi {'name'}!
  </code></pre>
  
  <p>Having no value for 'name' yet, the bot will first output 'Hi steve', and once the bot does have this value, the 'word' rule will apply. I'm not sure if this is easily feasible given the way I have structured my program. I have made it so that the text file is made into a dictionary with the key and value separated by the | character, when the user inputs some text, the program compares whether the user input matches the input stored in the dictionary, and prints out the corresponding bot response (there is also an 'else' case if no match is found). </p>
  
  <p>I must need something to happen at the comparing part of the process so that the user's regular expression text is saved and then substituted back into the dictionary somehow. All of my regular expressions have different names associated with them (there are no two instances of 'word', for example...there is 'word', 'word2', etc), I did this as I thought it would make this part of the process easier. I may have structured the thing completely wrong to do this task though. </p>
  
  <p>Edit: code</p>
  
  <pre><code>import re
  
  io = {}
  
  with open("rules.txt") as brain:
       for line in brain:
          key, value = line.split('|')
          io[key] = value
  
  string = str(raw_input('&gt; ')).lower()+' word'
  
  x = 1
  
  while x == 1:
      for regex, output in io.items():
          match = re.match(regex, string)
          if match:
              print(output.format(**match.groupdict()))
              string = str(raw_input('&gt; ')).lower()+' word'
      else:
          print ' Sorry?'
          string = str(raw_input('&gt; ')).lower()+' word'
  </code></pre>