Paul R
Paul R

Reputation: 2797

Regex from python list

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

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

Thank you.

Upvotes: 0

Views: 61

Answers (1)

TheF1rstPancake
TheF1rstPancake

Reputation: 2378

[] 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.

Upvotes: 2

Related Questions