Jump to content

A pattern for a unique match


fortnox007

Recommended Posts

Hi all,

 

Does anyone maybe know to solve the following. I am trying to make a pattern which should match the following between ' ' (that includes the | and the +  )

'1','2','5','6','7','1+','2+','5+','6+','7+','1|','2|','5|','6|'

 

But It should be an exact match so if someone types 12 its incorrect it should be either 1 or 2.

 

I tried this

preg_match ('/(1|2|5-6|1\+|2\+|5\+|6\+|7\+|1\||2\||5\||6\|){1}/');

But its not giving what i expect, it allready sucks at the start if someone enters12 it's true, while i would like it to be false.

 

Hope someone knows how to

           

Link to comment
https://forums.phpfreaks.com/topic/213697-a-pattern-for-a-unique-match/
Share on other sites

yes they are the pattern delimiters, just like your /../  I just prefer to use ~..~ because then I don't have to escape instances of / in a pattern, which is especially convenient when trying to parse html.

Ah that's smart : )

Oh last thing just to so I know i am reading your pattern right.

you made it unique by using the ^ at the start and $ in the end i assume. and made the second part less greedy by using the "?" behind it?

Okay so in this case, the ? is not entirely the same as "less greedy" (a.k.a "lazy").  What it means is "match 0 or 1 of the previous item or group".

 

~^(1|2|5|6|7)(\+|\|)?$~

 

[pre]

~          starting delimiter

^          signifies the beginning of the string

(1|2|5|6|7) match 1 or 2 or 5 or 6 or 7

(\+|\|)    match a literal + or |

?          make the previous thing optional. In this case, it is the + or |

$          signifies the end of the string

~          ending delimiter

[/pre]

 

So overall, it is matching a single number, followed by a an optional plus or pipe, and the ^ and $ are start and ending string anchors to signify the whole string ($number) can only be just one number and an optional + or |

Oh wow thanks alot! And sorry for asking this much.

I just watched the video about regex. It's better than sudoku's  ::)

http://phpvideotutorials.com/app/webroot/regex/

But there are quite some rules indeed : ) I am going to watch it a few times I guess and buy a book about it.

 

Thank you!

;)

If it makes you feel any better, most programmers (even professional programmers) run the other way at the mention of regex. It has a big learning curve.  But if you keep at it, one day it will just click and make sense, like you have to overcome some event horizon or somethin'. After that it is pretty easy and you wonder why it seemed so hard before.

 

IMO regex is one of the sexiest things about programming, but maybe that's just me :P

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.