8

I have following:

temp = "aaaab123xyz@+"

lists = ["abc", "123.35", "xyz", "AND+"]

for list in lists
  if re.match(list, temp, re.I):
    print "The %s is within %s." % (list,temp)

The re.match is only match the beginning of the string, How to I match substring in between too.

3 Answers 3

14

You can use re.search instead of re.match.

It also seems like you don't really need regular expressions here. Your regular expression 123.35 probably doesn't do what you expect because the dot matches anything.

If this is the case then you can do simple string containment using x in s.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, yours is 5 seconds faster actually, +1
13

Use re.search or just use in if l in temp:

Note: built-in type list should not be shadowed, so for l in lists: is better

1 Comment

I would have to agree for simple substring matching in is a lot easier than re.search.
0

You can do this with a slightly more complex check using map and any.

>>> temp = "aaaab123xyz@+"
>>> lists = ["abc", "123.35", "xyz", "AND+"]
>>> any(map(lambda match: match in temp, lists))
True
>>> temp = 'fhgwghads'
>>> any(map(lambda match: match in temp, lists))
False

I'm not sure if this is faster than a compiled regexp.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.