tags:

views:

19

answers:

2

Is it possible to use an input() with regex

I've written something like this

import re
words = ['cats', 'cates', 'dog', 'ship']

for l in words:
   m = re.search( r'cat..', l)  
   if m:
      print l
   else:
      print 'none'

this will return 'cates'

But now I want to be able to use my own input() in ' m = re.search( r'cat..', l) '

something like

import re
words = ['cats', 'cates', 'dog', 'ship']

target = input()

for l in words:
   m = re.search( r'target..', l)  
   if m:
      print l
   else:
      print 'none'

this doesn't work of course (I know it will search for the word 'target' and not for the input()). Is there a way to do this or are'nt regular expressions not the solution for my problem?

A: 

You could construct the RegEx dynamically:

target = raw_input()   # use raw_input() to avoid automatically eval()-ing.
rx = re.compile(re.escape(target) + '..')
                       # use re.escape() to escape special characters.

for l in words:
   m = rx.search(l)

....

But it is also possible without RegEx:

target = raw_input()

for l in words:
   if l[:-2] == target:
     print l
   else:
     print 'none'
KennyTM
OK this works but is this also possible with the other Regex patterns + ? . * ^ $ ( ) [ ] { } | \ how can I find all the words that start with 'ca' for example. I understand how those patterns work, but my problem is to make them work with an input() so that a user can himself chose his input()Ps I don't expect you to do all this work but if you could direct me to a site or a tutorial or anything that could help me ...
Preys
@Preys: http://docs.python.org/library/stdtypes.html#str.startswith
KennyTM
A: 

OK this works but is this also possible with the other Regex patterns + ? . * ^ $ ( ) [ ] { } | \ how can I find all the words that start with 'ca' for example. I understand how those patterns work, but my problem is to make them work with an input() so that a user can himself chose his input()

Ps I don't expect you to do all this work but if you could direct me to a site or a tutorial or anything that could help me ...

Preys