如何制作一个只有n,m字符的单词的正则表达式

发布于 2025-01-18 00:39:13 字数 322 浏览 1 评论 0原文

如果我在 file 中有以下内容:

watermelon
banana
apple
pineapple
apppppple

如何构造正则表达式,以便它只显示最少 2 个、最多 4 个连续“p”字符的单词?我尝试过

egrep 'p{2,4}' file

,但这包括我不想要的apppppple。

[root@localhost ~]# egrep 'p{2,4}' file
apple
pineapple
apppppple

If I have the following contents in file:

watermelon
banana
apple
pineapple
apppppple

How do I construct the regex so that it only shows me words where there is a minimum of 2 and a maximum of 4 consecutive 'p' characters? I tried

egrep 'p{2,4}' file

but this includes apppppple, which I do not want.

[root@localhost ~]# egrep 'p{2,4}' file
apple
pineapple
apppppple

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

杀お生予夺 2025-01-25 00:39:13

您可以使用

grep -E '([^p]|^)p{2,4}([^p]|$)' file # POSIX ERE regex flavor
grep -P '(?<!p)p{2,4}(?!p)' file      # PCRE regex flavor, GNU grep only

([^p]|^) 部分匹配除 p 以外的任何字符或字符串开头,以及 ([^p]|$) 匹配除 p 或字符串结尾之外的任何字符。

(? 模式匹配前面或后面都没有 < 的两个、三个或四个 p代码>p。

请参阅在线演示

#!/bin/bash
s='watermelon
banana
apple
pineapple
apppppple'
grep -E '([^p]|^)p{2,4}([^p]|$)' <<< "$s"

输出:

apple
pineapple

You can use

grep -E '([^p]|^)p{2,4}([^p]|$)' file # POSIX ERE regex flavor
grep -P '(?<!p)p{2,4}(?!p)' file      # PCRE regex flavor, GNU grep only

The ([^p]|^) part matches any char other than p or start of string, and ([^p]|$) matches any char other than p or end of string.

The (?<!p)p{2,4}(?!p) pattern matches two, three or four ps that are not preceded nor followed with p.

See the online demo:

#!/bin/bash
s='watermelon
banana
apple
pineapple
apppppple'
grep -E '([^p]|^)p{2,4}([^p]|$)' <<< "$s"

Output:

apple
pineapple
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文