简体   繁体   English

限制正则​​表达式中的位数

[英]Limit the number of digits in regex

I have such a regex: 我有这样的正则表达式:

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

It matches the following strings: 它匹配以下字符串:

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

I want to limit the number of digits in this regex to 8. 我想将此正则表达式中的位数限制为8。

Tried this: 试过这个:

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

It stopped matching anything. 它停止匹配任何东西。

What am I doing wrong? 我究竟做错了什么?

\d{, 8}

Means nothing .Engine will match it literally and so your regex failed. 什么都没有.Engine会字面上匹配,所以你的正则表达式失败了。

Use 使用

\d{0,8}

No spaces inside {} {}内没有空格

The {} has three form: {}有三种形式:

  • {N} for a fixed number of time {N}一段固定的时间
  • {M,} for at least M times {M,}至少M次
  • {N,M} for between N and M times. {N,M}为N和M倍。

If you use the last one, the minimum is mandatory. 如果您使用最后一个,则必须使用最小值。

Change your regex to \\d{1,8} to match between 1 and 8 times a digit 将正则表达式更改为\\d{1,8}以匹配一位数的1到8次

Starting with 1 as you were using + which is a shortcut for {1,} 当你使用+时从1开始,这是{1,}的快捷方式

Have a look at what regex101.com says: 看看regex101.com的内容

在此输入图像描述

You can use the {1,8} limiting quantifier that will match 1 to 8 digits. 您可以使用匹配1到8位的{1,8}限制量词。 I see there must be at least 1 since you have + in your original regex. 我看到必须至少有1个,因为你的原始正则表达式中有+

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

See demo 演示

From the regular-expressions.info : 来自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. 语法为{min,max} ,其中min为零或表示最小匹配数的正整数, max为等于或大于min的整数,表示最大匹配数。 If the comma is present but max is omitted, the maximum number of matches is infinite. 如果逗号存在但省略了max ,则最大匹配数为无限。 So {0,1} is the same as ? 所以{0,1}?相同? , {0,} is the same as * , and {1,} is the same as + . {0,}*相同, {1,}+相同。 Omitting both the comma and max tells the engine to repeat the token exactly min times. 既省略逗号和max告诉引擎正好重复令牌min时间。

Try to specify lower bound like (\\d{0,8}) . 尝试指定下限(\\d{0,8})

Besides some regex dialects do not allow whitespace after comma in {0,8} construction. 除了一些正则表达式方言在{0,8}构造中逗号后不允许空格。

You need to set a lower limit as well. 您还需要设置下限。

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

You can see a demo here 你可以在这里看到一个演示

Also specify the lower limit 同时指定下限

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

This would work. 这会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM