Regexp returns true, but the author of the book says he should not

Reading an online PHP resource about Regexp (TuxRadar). According to the author, the following should not match the "aaa1" pattern and therefore returns false (0), but I believe (1).

<?php

$str = "aaa1";
print preg_match("/[a-z]+[0-9]?[a-z]{1}/", $str);

?>

Why?

Regular expressions

+3
source share
3 answers

Are you sure there should not be trailing $? Without it, returning true makes a lot of sense - the first block [a-z]matches the first two characters a, [0-9]nothing matches, and the last [a-z]matches the 3rd a. The ultimate is 1ignored.

Looking at the link to the book, there seems to be an error:

Must end with a lowercase letter

, $.

+7

, [0-9]? .

<?php
$str = "aaa1";
print preg_match("/[a-z]+[0-9]+[a-z]{1}/", $str);
?>

.

+3

Lets break regular expression

  • [az] + means one or more letters that are gready that match a, aa or aaa
  • [0-9]? means optional - so it can match a digit
  • [az] means matching a letter, which may be

Therefore, due to the fact that [0-9] is optional, 1 will correspond to aa, 2 will correspond to nothing, and 3 will correspond to a

+2
source

All Articles