Simple RegEx Pattern- Help with the last bit

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

Moderator: General Moderators

Post Reply
magnetica2
Forum Newbie
Posts: 3
Joined: Wed Oct 19, 2011 7:33 am

Simple RegEx Pattern- Help with the last bit

Post by magnetica2 »

Hi All

Need a little help with my RegEx, I am half way there but can't figure out the last bit

I want the Regex to match.

123-456-789

I don't mind how long the numbers are, but the dashes in the middle can only be 1 long

My regex so far
([^-]([0-9]+[^-]))

This matches
123-456-789
but will also match
123-456----789

I just need the Regex to only allow 1 dash in the middle

Thanks for any help
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Simple RegEx Pattern- Help with the last bit

Post by Apollo »

magnetica2 wrote:My regex so far
([^-]([0-9]+[^-]))
^ between [ ] means "not". So you're actually matching: any char except dash, followed by one or more digits, followed by any char except dash again. Even just "123" will match this pattern already.

Try this:

Code: Select all

preg_match( '#^[0-9]+-[0-9]+-[0-9]+$#', $yourString );
This regexp means: one or more digits, one dash, one or more digits, one dash, one or more digits.
magnetica2
Forum Newbie
Posts: 3
Joined: Wed Oct 19, 2011 7:33 am

Re: Simple RegEx Pattern- Help with the last bit

Post by magnetica2 »

Thanks but that restricts me to 3 sections
I found the right Regex
[\d]+(-[\d]+)*
magnetica2
Forum Newbie
Posts: 3
Joined: Wed Oct 19, 2011 7:33 am

Re: Simple RegEx Pattern- Help with the last bit

Post by magnetica2 »

LOL. This Regex works but because im using it in the CodeIgniter frameworks Routes.php

The braces within braces mess it all up? Any ideas?
Post Reply