【问题标题】:I need to match the list of elements with the following pattern我需要将元素列表与以下模式匹配
【发布时间】:2018-12-26 18:36:15
【问题描述】:

模式:arl$en

以arl 开头 以en结尾

$可以是任意字{"a" - "z", "0123456789", ". , ! ? :"}

有效例子:

arlen
arl!?en
arlwerwen
arlren
arl.en
arl?en
arl0123.en
arl1en

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你可以在 python 中使用:r'^arl[a-z0-9,.!?:]*en$'。
  • 试试regex101.com

标签: python regex


【解决方案1】:

您可以编写一个函数来依次检查条件,如下面的代码。它检查字符串是否以您想要的模式开始和结束,如果是这样,它检查中间的所有字符是否都是您定义的字符集的一个元素。 代码:

def checkstring(s):
    if not (s.startswith("arl") and s.endswith("en")):
        return False
    for i in s[3:-2]:
        if not i in "1234567890abcdefghijklmnopqrstuvwxyz.,?!:":
            return False
    return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多