限制regex中的位数

2024-04-23 11:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个正则表达式:

'(?:\$|сум)(\040)?(\d+)|(\d+)(\040)?(?:\$|сум)'

它匹配以下字符串:

$23
23$
1000сум
сум1000
сум 1000
1000 сум

我想把这个正则表达式中的位数限制为8。

试过这个:

'(?:\$|сум)(\040)?(\d{, 8})|(\d{, 8})(\040)?(?:\$|сум)'

它不再匹配任何东西。

我做错什么了?


Tags: 字符串位数
3条回答
\d{, 8}

没有任何意义。引擎将匹配它字面上,所以你的正则表达式失败。

使用

\d{0,8}

{}内没有空格

看看regex101.com怎么说:

enter image description here

您可以使用{1,8}限制量词,它将匹配1到8位数字。我知道至少有一个,因为您的原始regex中有+

^(?:(?:\$|сум)(\040)?(\d{1,8})|(\d{1,8})(\040)?(?:\$|сум))$

demo

regular-expressions.info

The syntax is {min,max}, where min is zero or a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. If the comma is present but max is omitted, the maximum number of matches is infinite. So {0,1} is the same as ?, {0,} is the same as *, and {1,} is the same as +. Omitting both the comma and max tells the engine to repeat the token exactly min times.

{}有三种形式:

  • {N}固定时间
  • {M,}至少M次
  • {N,M}持续N到M次。

如果使用最后一个,则最小值是必需的。

将regex改为\d{1,8}以匹配1到8倍的数字

从1开始,因为您正在使用+这是{1,}的快捷方式

相关问题 更多 >