jlmmns
jlmmns

Reputation: 845

Regex match number consisting of specific range, and length?

I'm trying to match a number that may consist of [1-4], with a length of {1,1}.

I've tried multiple variations of the following, which won't work:

/^string\-(\d{1,1})[1-4]$/

Any guidelines? Thanks!

Upvotes: 0

Views: 95

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

You should just use:

/^string-[1-4]$/

Match the start of the string followed by the word "string-", followed by a single number, 1 to 4 and the end of the string. This will match only this string and nothing else.

If this is part of a larger string and all you want is the one part you can use something like:

/string-[1-4]\b/

which matches pretty much the same as above just as part of a larger string.

You can (in either option) also wrap the character class ([1-4]) in parentheses to get that as a separate part of the matches array (when using preg_match/preg_match_all).

Upvotes: 1

Ruben Kazumov
Ruben Kazumov

Reputation: 3892

This is not hard:

/^string-([1-4]{1})$/

Upvotes: 1

Related Questions