在两个相等的符号之间获取字符串

时间:2016-12-30 02:54:06

标签: python regex

我正在尝试使用Python的RE来获取两个等号(=helloThere=)之间的信息,但不能获得多于​​一个等号(==helloThere==)之间的信息。

这是我到目前为止所提出的,但它并没有这样做:

result = re.findall('={1}(.*?)={1}', text)

2 个答案:

答案 0 :(得分:5)

使用负面的后观和负面的前瞻。

>>> import re
>>> re.findall(r'(?<!=)=([^=]+)=(?!=)', '=hello there=')
['hello there']
>>> re.findall(r'(?<!=)=([^=]+)=(?!=)', '==hello there==')
[]

答案 1 :(得分:0)

如果您只有这两个条件:

1 - 以=为开始和结束 2 - 应该只有两个=

然后这是我对你的建议:

s = '=helloThere='
test_char = '='
if (s[0] == s[-1] == test_char) and s.count('=') == 2:
    print(s[1:-1])
    # or print(s.strip('=')

如果=之间的表达式不包含其他=,则此选项有效。