0

Today, I found out that regex r"['a', 'b']" matches 'a, b'.

Why is that? What does comma and ' mean inside []?

Thank you.

4
  • Can we see the implementation of the regex? Commented Nov 7, 2016 at 15:39
  • Have you tried reading the documentation docs.python.org/2/library/re.html ? Commented Nov 7, 2016 at 15:39
  • 12
    ['a', 'b'] is the same as [',ab] Commented Nov 7, 2016 at 15:39
  • Possible duplicate of Reference - What does this regex mean? Commented Nov 7, 2016 at 15:53

1 Answer 1

2

[] is used to define character sets in regular expressions. The expression will match if the string contains any of the characters in that set.

Your regular expression:

 r"['a', 'b']"

Says "match if string contains ' or a or , or b. As @Patrick Haugh mentions in his comment. Your expression is equivalent to [',ab]. Repeating the same character in the set does nothing.

http://www.regexpal.com/ is a great site for testing your regular expressions. It can help break it down for you and explain what your expression does and why it matches on certain strings.

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

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.