Reputation: 13763
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
Reputation: 627607
Have a look at what regex101.com says:
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}
, wheremin
is zero or a positive integer number indicating the minimum number of matches, andmax
is an integer equal to or greater thanmin
indicating the maximum number of matches. If the comma is present butmax
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 exactlymin
times.
Upvotes: 6
Reputation: 22121
Also specify the lower limit
(?:\$|сум)(\040)?(\d{1,8})|(\d{1,8})(\040)?(?:\$|сум)
This would work.
Upvotes: 2
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
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
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
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