Regexp matching equal number of the same character on each side of a string
How do you match only equal numbers of the same character (up to 3) on each side of a string in python?
For example, let's say I am trying to match equal signs
=abc=
or ==abc==
or ===abc===
but not
=abc==
开发者_运维问答or ==abc=
etc.
I figured out how to do each individual case, but can't seem to get all of them.
(={1}(?=abc={1}))abc(={1})
as |
of the same character
((={1}(?=abc={1}))|(={2}(?=abc={2})))abc(={1}|={2})
doesn't seem to work.
Use the following regex:
^(=+)abc\1$
Edit:
If you are talking about only max three =
^(={1,3})abc\1$
This is not a regular language. However, you can do it with backreferences:
(=+)[^=]+\1
consider that sample is a single string, here's a non-regex approach (out of many others)
>>> string="===abc==="
>>> string.replace("abc"," ").split(" ")
['===', '===']
>>> a,b = string.replace("abc"," ").split(" ")
>>> if a == b:
... print "ok"
...
ok
You said you want to match equal characters on each side, so regardless of what characters, you just need to check a
and b
are equal.
You are going to want to use a back reference. Check this post for an example:
Regex, single quote or double quote
精彩评论