【问题标题】:Python regex find all single alphabetical charactersPython正则表达式查找所有单个字母字符
【发布时间】:2013-04-23 12:50:52
【问题描述】:

我想查找字符串中每次出现单个字母字符的所有索引。我不想捕获单个 char html 代码。

这是我的代码:

import re
s = "fish oil B stack peanut c <b>"
words = re.finditer('\S+', s)
has_alpha = re.compile(??????).search
for word in words:
    if has_alpha(word.group()):
        print (word.start())

期望的输出:

9
24

【问题讨论】:

  • 感谢所有提供帮助的正则表达式天才。

标签: python regex character alphabetical


【解决方案1】:

这样做:

r'(?i)\b[a-z]\b'

分解:

  • 不区分大小写的匹配
  • 单词边界
  • 一封信
  • 单词边界

您的代码可以简化为:

for match in re.finditer(r'(?i)\b[a-z]\b', s):
   print match.start()

【讨论】:

  • 谢谢,但由于各种原因,我需要遵循我的问题中显示的结构。为此,我假设我只会使用 has_alpha = re.compile(r'(?i)\b[a-z]\b').search?
  • @user2104778:是的,绝对是。该正则表达式适用于您的原始代码以及我的简化示例。
  • 好的,我想我们快到了。您的解决方案很棒,除了它可以捕获像“”这样的 html 代码。如果可能的话,我想避免这种情况。有什么想法吗?
  • @user2104778: r'(?i)^[a-z]$' 将解决这个问题(在您的代码中,而不是在我的简单情况下)。
  • Richie,非常感谢您的帮助。您的解决方案适用于我使用的示例,但不适用于其他示例,请尝试前。 '菠萝水 ww2 Finetougch v ww2bd peterbuitl ww2b '。但是,如果您添加一个简单的 len 检查您的解决方案是否有效。
【解决方案2】:

使用您的格式 (as you wanted),但只添加一个简单的检查。

import re
s = "fish oil B stack peanut c <b>"
words = re.finditer('\S+', s)
has_alpha = re.compile(r'[a-zA-Z]').search
for word in words:
    if len(word.group()) == 1 and has_alpha(word.group()):
        print (word.start())
>>> 
9
24

【讨论】:

  • 好的,这是正确的解决方案。感谢 Inbar 和其他所有人。
【解决方案3】:

在最一般的情况下,我会说:

re.compile(r'(?i)(?<![a-z])[a-z](?![a-z])').search

使用lookarounds 表示“一个字母前面没有另一个字母,后面也没有另一个字母”。

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多