如何在Python中编写用于等值线检测的javascript正则表达式?

2024-09-30 03:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在另一篇SO文章中发现了一些使用Javascript的东西,但我想知道是否有与Python等效的东西

function isIsogram (str) {
    return !/(\w).*\1/i.test(str);
}

对于我的问题,我可以允许空格和连字符,但不能允许其他重复字符。 我原以为会是这样的,但很明显我已经走远了

def is_isogram(string: str):
    comp_re = re.compile(r'!/(\w).*\1/i')
    return comp_re.match(string)

Tags: testrestringreturnsoisdef文章
1条回答
网友
1楼 · 发布于 2024-09-30 03:23:30

在Python中,这可能是一个选项

注意,您不需要不区分大小写的标志,因为\w.同时匹配大写和小写字符a-z

import re

def isIsogram(s):
    return not re.search(r"(\w).*\1", s)

strings = [
    "dialogue",
    "a",
    "testing",
    "abcdb"

]
for s in strings:
    print(f"{s}  > {isIsogram(s)}")

输出

dialogue  > True
a  > True
testing  > False
abcdb  > False

Python demo


要匹配whitspace字符或连字符以外的任何字符,可以使用negated character class

([^-\s]).*\1

相关问题 更多 >

    热门问题