开发者

Regular expressions help

I am trying to write a regular expression in php that checks to make sure the string passed in is one of three things, however I am having a hard time (I really struggle with regex).

I need to make sure that my received parameter contains one of these three things, and nothing else:

  1. "|" and that's it just a single pipe OR
  2. "" and that's it just an empty string OR
  3. "|1|534|3453|23|213|2|" A long string that uses pipes as a delimiter for a series of numbers

Thank you for your help (this is continually a problem for me, think I need to buy a book exclusively on 开发者_如何转开发regex)


preg_match('/^(?:\|(?:\d+\|)*)?$/', $input);


The easiest way to do this would be to split it into three separate checks:

  1. The string is just a single pipe (strcmp($str,"|") == 0)
  2. The string is empty (strlen($str) == 0).
  3. The string matches the regex /^[0-9\|]+$/

Don't make it harder than it needs to be by trying to cram all of those checks into one regular expression. Your code will be more easily understood, and future maintainers of your code will thank you.

Edit: Just to display what I'm talking about, here's some sample code:

if( strcmp($str,"|") == 0 ||
    strlen($str) == 0     ||
    preg_match('^[0-9\|]+$', $str) {
  ...
}

vs

if( preg_match('/^(?:\|(?:\d+\|)*)?$/', $str ) {
  ...
}

At a glance, which one executes the ... if $str is empty?


(^(\|)([0-9\|]{0,})(\|)$)|(^(\|)$)|()

use above regex and if no mathches your string is not valid, othervise its valid, and try to check of empty if str_len($string) > 0 then check regex

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜