【问题标题】:How do I write this javascript regex for isogram detection In Python?如何在 Python 中编写这个用于等值图检测的 javascript 正则表达式?
【发布时间】:2021-05-19 23:12:49
【问题描述】:

我在另一个 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)

【问题讨论】:

  • ! 不是正则表达式的一部分,它是 JavaScript 中的 not 运算符。
  • 正则表达式不适合检测等值线(可能是一阶的除外)。
  • 喜欢def isIsogram(s): return not re.search(r"(\w).*\1", s) ?
  • 如果空格和连字符是唯一允许重复的字符,请将 \w 更改为 [^- ]。
  • @Carcigenicate 您的正则表达式足够强大,请给出答案。

标签: python python-3.x regex


【解决方案1】:

在 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


要匹配除空白字符或连字符以外的任何字符,您可以使用negated character class:

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

【讨论】:

  • 谈案例:“奥斯陆”是等值线吗?
  • 非常感谢!你和@Barmar 非常有帮助。最终我选择了以下内容:def is_isogram(string: str): comp_re = re.compile(r'([^- ]).*\1', re.IGNORECASE) return not comp_re.search(string)
  • @Joffan 老实说,我不知道那是什么规则。
  • 我的回答有几个测试失败,因为这是因为大小写。此外,[^-] 允许使用连字符和空格。
  • @Thefourthbird 是的,将我的问题标记到你的答案上可能不公平......如果“奥斯陆”不是等值线,我猜 isIsogram(s) 中的 return not re.search(r"(\w).*\1", s.lower()) 会修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
相关资源
最近更新 更多