perl - 如何只匹配几个数字?
问题描述
目前,我有一个问题只能匹配几个数字。
例如:
my $input1 = "1234 abc test"; - > expect - match and return 1234
my $input2 = " 1234 abc test"; - > expect - match and return 1234
my $input3 = "abc test 1234"; - > expect - match and return 1234
my $input4 = "a1234 test"; not match
my $input5 = "1234- abc test"; not match
my $input6 = "abc 12345 test"; not match
对于以上 6 个示例,只有 input1、input2 和 input3 需要 return 1234
。其他人将返回not matched
。如何编写这样的正则表达式?
我尝试这样做,但它不适用于 input1 和 input3。
if $input =~ /\s+(\d{4,4})\s+/{
}
解决方案
/(?:^|\s)(\d{4})(?:\z|\s)/a
或者
/(?<!\S)(\d{4})(?!\S)/a # Not proceeded by a non-space and not followed by a non-space.
(\d
通常匹配 630 个不同的代码点。/a
导致它只匹配[0-9]
。)
推荐阅读
- flutter - 在 Flutter 中将 forEach 循环转换为 Future.forEach 循环
- javascript - 在js中转换数组数据
- r - ggplot:将方程添加到刻面环绕条
- json - 需要使用 JOLT 将 JSON 转换为特定的 JSON
- c# - 进程 WaitForExit 没有响应
- python - 来自 azure repos 的 Azure 函数导入模块
- java - 无法在索引 0 1/1/2020 12:12:12 MM/dd/yyyy HH:mm:ss 处解析文本“2020 年 1 月 1 日 12:12:12”
- python - Django 选择在模型的保存方法中加载图像的位置
- ip - 怎么给电脑设置静态ip
- python - 转换为列表后枚举对象为空