开发者

Why both of my PHP regexp fail?

$subject = "SPRINT-1.csv开发者_StackOverflow社区";
$pattern = '/^[a-zA-Z]\-[0-9]\.(csv)+$/';
if(preg_match($pattern, $subject)) {
 echo "Match";
} else {
 echo "NOPE";
}

or

$subject = "SPRINT-1.csv";
$pattern = '/^\w\-\.(csv)+$/';
if(preg_match($pattern, $subject)) {
 echo "Match";
} else {
 echo "NOPE";
}


A character class […] does only describe one single character. So [a-zA-Z] describes one character out of az, AZ. The same applies to \w (that’s also a character class).

You forgot to describe the quantity the characters from that character classes may appear, like:

  • ?: zero or one repetition
  • *: zero or more repetitions
  • +: one or more repetitions


'/^[a-zA-Z]\-[0-9]\.(csv)+$/'; you're missing the quantifier, it should be [a-zA-Z]+ or [a-zA-Z]*.

Try out http://www.regexp.net/ to quickly optimize your regexp.


<?
$subject = "SPRINT-1.csv";
$pattern = '/^[a-zA-Z]*\-[0-9]\.csv?$/';
if(preg_match($pattern, $subject)) {
 echo "Match";
} else {
 echo "NOPE";
}
?>


You can do either:

preg_match_all('/^[a-zA-Z]+\-[0-9]\.csv$/i', 'SPRINT-1.csv', $result);

or

preg_match_all('/^\w+\-\d\.csv+$/i', 'SPRINT-1.csv', $result);

In both case, you forgot the "+" before the letters that match "SPRINT", in the second case, you forgot the number to match "1".

And by the way, you don't need the "+" at the end of the pattern, nor the () around the csv.

But please, make an effort to write a complete question. Posting just code like that is not really handy to understand.

Finally, if you want to test regexp, use a good tool.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜