使用正则表达式查找长度为 4 的单词 [英] find words of length 4 using regular expression

查看:50
本文介绍了使用正则表达式查找长度为 4 的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在正则表达式中查找长度为 4 的单词

我正在尝试这个,但我得到一个空列表:

#长度为4的单词s = input("请输入一个表达式:")打印(re.findall(r'/^[a-zA-Z]{4}$/',s))

我的代码有什么问题?

我的输入是:这些天我们玩得很开心

我的预期输出:['here', 'days']

我的输出:[]

解决方案

使用单词边界 \b.当您在正则表达式中添加锚点时,例如 ^[a-zA-Z]{4}$,这将匹配只有四个字母的行.它不会检查每个单独的单词.^ 断言我们在开始,$ 断言我们在结束.\b 匹配单词字符和非单词字符(反之).因此它匹配单词的开头(零宽度)或单词的结尾(零宽度).

<预><代码>>>>s = "这几天我们玩得很开心">>>re.findall(r'\b[a-zA-Z]{4}\b', s)['这里','天']

I am trying to find words in regular expression with length 4

I am trying this but I am getting an empty list:

#words that have length of 4
s = input("please enter an expression: ")
print(re.findall(r'/^[a-zA-Z]{4}$/',s))

What is wrong with my code ?

my input is: here we are having fun these days

my expected output: ['here', 'days']

my output: []

解决方案

Use word boundaries \b. When you add anchors in your regex like ^[a-zA-Z]{4}$, this would match the lines which have only four alphabets. It won't check for each individual words. ^ asserts that we are at the start and $ asserts that we are at the end. \b matches between a word character and a non-word character(vice versa). So it matches the start (zero width) of a word or end (zero width) of a word.

>>> s = "here we are having fun these days"
>>> re.findall(r'\b[a-zA-Z]{4}\b', s)
['here', 'days']

这篇关于使用正则表达式查找长度为 4 的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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