Python正则表达式查找所有单个字母字符 [英] Python regex find all single alphabetical characters

查看:1878
本文介绍了Python正则表达式查找所有单个字母字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to find all indexes for each occurrence of single alphabetical characters in a string. I don't want to catch single char html codes.

这是我的代码:

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


推荐答案

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

Using your format (as you wanted) but adding only a simple check.

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

这篇关于Python正则表达式查找所有单个字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆