Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13763

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.

Tried this:

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

It stopped matching anything.

What am I doing wrong?

Upvotes: 16

Views: 32395

Answers (6)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Have a look at what regex101.com says:

enter image description here

You can use the {1,8} limiting quantifier that will match 1 to 8 digits. I see there must be at least 1 since you have + in your original regex.

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

See demo

From the 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.

Upvotes: 6

Anuj More
Anuj More

Reputation: 22121

Also specify the lower limit

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

This would work.

Upvotes: 2

Tensibai
Tensibai

Reputation: 15784

The {} has three form:

  • {N} for a fixed number of time
  • {M,} for at least M times
  • {N,M}for between N and M times.

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

Starting with 1 as you were using + which is a shortcut for {1,}

Upvotes: 16

Oleksii Lotysh
Oleksii Lotysh

Reputation: 363

Try to specify lower bound like (\d{0,8}).

Besides some regex dialects do not allow whitespace after comma in {0,8} construction.

Upvotes: 3

vks
vks

Reputation: 67998

\d{, 8}

Means nothing .Engine will match it literally and so your regex failed.

Use

\d{0,8}

No spaces inside {}

Upvotes: 13

user142650
user142650

Reputation:

You need to set a lower limit as well.

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

You can see a demo here

Upvotes: 1

Related Questions