0

I have two strings PG((0,0), (0,1), (1,1), (1,0)) and P(1,1)
I need to write code that would identify those string with the help of a regular expression.

So far I have this:

if(re.search("^[P\(]",line) is not None):
    print "P found"

This identifies both strings, but should only identify P(1,1)

if(re.search("^[PG\(\(]",line) is not None):
    print "PG found"

This also identifies both strings, but should only identify PG((0,0), (0,1), (1,1), (1,0))

What am I doing wrong here?

1
  • 1
    Why are you using character classes ([])? It seems to me that it should work if you remove those. Commented May 16, 2013 at 22:22

2 Answers 2

3

your regular expressions are using character classes (the stuff inside []). This means, "match any of these characters". so, you're first one matches any string which starts with "P" or "(" and your second one matches any string which starts with "P","G" or "(". The easiest fix is to remove the character class -- e.g.:

re.search(r"^PG\(\(",line)

Note that I've used a "raw string" (a string prefixed by r). This prevents python from doing it's usual escaping of characters. Also note that if you change from using re.search to re.match, you can get rid of the beginning of the line anchor:

re.match(r"PG\(\(",line)

as re.match only works starting from the beginning of the string. It simplifies the regex slightly which, when dealing with regex I feel like every possible simplification is worth it. On that note, you could even forgo the regex all together here and just use str.startswith:

if line.startswith('PG(('):
   ...
elif line.startswith('P('):
   ...
Sign up to request clarification or add additional context in comments.

Comments

0

Remove square brackets, as they mark character sets. Use:

if(re.search(r"^P\(",line) is not None):

The reason why the previous version was matching both expressions is that it would test for P or \(, and both contain an opening bracket.

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.