regex - Bash:如何提取字符串中所有“n”位数字的计数?
问题描述
我正在尝试使用 bash 从字符串中提取 n 位数字的总数。
例如,对于 3 位数字,
I am trying to extract 3 digited numbers 333, 334, 335 from this string #should return 3
I have 243 pens for sale #should return 1
不幸的是,我将无法使用sed
or grep
with perl-regexp
。
感谢任何建议!
解决方案
您可以在 bash 中使用正则表达式。
#! /bin/bash
cat <<EOF |
I am trying to extract 3 digited numbers 333, 334, 335 from this string #should return 3, but should ignore 12345
I have 243 pens for sale #should return 1
123 should work at text boundaries, too 123
EOF
while read line ; do
c=0
while [[ $line =~ ([^[:digit:]]|^)([0-9][0-9][0-9])([^[:digit:]]|$) ]] ; do
m=${BASH_REMATCH[0]}
line=${line#*$m}
((++c))
done
echo $c
done
正则表达式解释:
([^[:digit:]]|^)([0-9][0-9][0-9])([^[:digit:]]|$)
~~~~~~~~~~~~~ non-digit
~~ or the very beginning
~~~~~~~~~~~~~~~ three digits
~~~~~~~~~~~~ non-digit
~~ or the very end
由于 bash 不能多次匹配同一个字符串,我们需要在尝试另一个匹配之前从字符串中删除已经处理的部分。
推荐阅读
- python - Django Rest 框架响应
- python - 使用 TCP 进行套接字编程三向握手 (PYTHON)
- amazon-ecs - 如何在容器环境变量的 ECS 任务定义中设置机密?
- amazon-s3 - 如何使用 aws cli 阻止对我的所有存储桶的公共访问?
- javascript - 我应该如何使用 javascript 过滤 JSON?
- python - Selenium 找不到类
- excel - 加快/改进此 VBA 脚本的建议?
- reactjs - 如何为简单的 Fulcro 应用程序设置动态 UI 路由
- html - 如果隐藏了该广告,则不支持通过该广告设置的 HTML 列宽
- c++ - 如何用模板替换多态性原则以拥有通用数据库?