Neden benim PHP regexp hem başarısız?

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

veya

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

3 Cevap

Bir karakter sınıfı […] sadece tek bir karakteri tarif etmez. z, A - - Yani [a-zA-Z] ve a dışında bir karakteri anlatır Z. Aynı \w (bu da bir karakter sınıfı bulunuyor) için geçerlidir.

O karakter sınıfları karakterler gibi görünebilir miktarını açıklamak için unuttum:

  • ? : sıfır ya da bir tekrarlama
  • * : sıfır veya daha fazla tekrarlar
  • + : Bir veya daha fazla tekrarlar

'/^[a-zA-Z]\-[0-9]\.(csv)+$/'; Eğer nicelik kaçırıyorsun, bu [a-zA-Z]+ veya [a-zA-Z]* olmalıdır.

http://www.regexp.net/ hızlı regexpi optimize etmek için deneyin.

Sen birini yapabilirsiniz:

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

veya

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

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

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

But please, make an effveyat 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.