1

I tried running the following code:

lin = ',11'
pat = ',([11|01])$'
re.search(pat, lin)

since pat has ',11' and lin also has ',11' I should get an object returned by re.search

But in this case, it is returning None.

Can anybody please help me out? I'm pretty confused over it.

0

4 Answers 4

5

You are using a character class: [...]. These act as sets; any of the characters you name in them will match. Your character class will match any 1, | or 0 character, the 3 unique characters you named in the class. You didn't specify a multiplier after the [...] character class, so it'll match just one character:

>>> re.match(',([11|01])$', ',1')
<_sre.SRE_Match object at 0x1106d1648>
>>> re.match(',([11|01])$', ',0')
<_sre.SRE_Match object at 0x1106d16c0>
>>> re.match(',([11|01])$', ',|')
<_sre.SRE_Match object at 0x1106d1648>

Remove the class if you want to match exact characters:

pat = ',(11|01)$'

which matches either the literal characters 11 or 01:

>>> re.match(',(11|01)$', ',11')
<_sre.SRE_Match object at 0x1106d16c0>
>>> re.match(',(11|01)$', ',01')
<_sre.SRE_Match object at 0x1106d1648>

or, if you still want to use a character class:

pat = ',([01]1)$'

Now the parenthesis are no longer required to group the | or operator, so you can drop those to simplify things down to:

pat = ',[01]1$'

Demo:

>>> re.match(',[01]1$', ',01')
<_sre.SRE_Match object at 0x1106bc5e0>
>>> re.match(',[01]1$', ',11')
<_sre.SRE_Match object at 0x1106bc648>
>>> re.match(',[01]1$', ',00') is None
True
>>> re.match(',[01]1$', ',10') is None
True
>>> re.match(',[01]1$', ',|') is None
True
Sign up to request clarification or add additional context in comments.

Comments

4

Due to the [...] brackets, your regular expression matches one character, which may be 0, 1, or |.

I think you wanted more like ,(11|01)$.

Comments

2

This works:

re.search(r',(11|01)',lin)

Comments

0

[11|01] is not 11 or 01, it is actually 1 or | or 0.

Try using this:

,[10]1$

That would be a comma, then [1 or 0], then 1, then an anchor to the end of string.

You could also just use this:

,((11)|(01))$

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.