Matching number of characters

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
thatsme
Forum Commoner
Posts: 87
Joined: Sat Apr 07, 2007 2:18 am

Matching number of characters

Post by thatsme »

How to check,

number-number-number-number-number-number

6 times numbers (any numbers (single, double, three digit etc)) followed by an hyphen, -

Code: Select all

if (preg_match ( "/^[0-9](-[0-9])*$/" , $str ) )
{
// match!
}
else
{
// doesn't match
}
it fails when i give 2, 3 digits.
User avatar
arjan.top
Forum Contributor
Posts: 305
Joined: Sun Oct 14, 2007 4:36 am
Location: Hoče, Slovenia

Re: Matching number of characters

Post by arjan.top »

If you have [0-9] it will match only one character/digit, you have to write something like that [0-9]+, it will match numbers with one or more digits

And If you have number-number-number-number-number-number all the time you may want to use {5}, so it wont match
number-number-number-number-number-number-number

Somethin like that:

Code: Select all

"/^[0-9]+(-[0-9]+){5}$/"
thatsme
Forum Commoner
Posts: 87
Joined: Sat Apr 07, 2007 2:18 am

Post by thatsme »

Thanks arjan.top,

i wanted the number any number of times and removed,

{5}
from

Code: Select all

"/^[0-9]+(-[0-9]+){5}$/"
and tested using below code,

Code: Select all

"/^[0-9]+(-[0-9]+)$/"
it fails even if i give, 6 numbers.
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

vigge89 wrote:In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/
I think you're after the asterisk, not the plus.
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

superdezign wrote:
vigge89 wrote:In the second pattern you missed adding the plus sign after the repetitive subpattern;

Code: Select all

/^[0-9]+(-[0-9]+)+$/
I think you're after the asterisk, not the plus.
Ah yeah, my bad:

Code: Select all

/^[0-9]+(-[0-9]+)*$/
vapoorize
Forum Newbie
Posts: 22
Joined: Mon Dec 17, 2007 5:35 pm

Post by vapoorize »

^ and $ are taken as string literals in preg if you don't add the m modifier, so it should be this if you mean to say the start and end of the line by those characters:

Code: Select all

/^[0-9]+(-[0-9]+)*$/m
Post Reply