Why preg_match(“/[^(22|75)]/”, “25”) returns false?

前端 未结 5 1526
误落风尘
误落风尘 2021-01-29 08:31

I want to test that a given string does not belong to the following group of strings: 22 75.

Could anyone please tell why PHP\'s preg_match(\"/[^(22|75)]/\

5条回答
  •  情歌与酒
    2021-01-29 09:19

    Time for a Regular Expressions Lesson!


    Explanation of your regular expressions

    [^(22|75)]

    Matches false because it is looking for the following:

    • A single character NOT in this list of characters: |()275

    [^(22|76)]

    Matches true because it is looking for:

    • A single character NOT in this list of characters: |()276

    Why does it do this?

    You wrapped your regex in a character class (click for more info)

    To give an example of how character classes work, look at this regex:

    [2222222222222221111111199999999999]

    This character class will only match ONE character, if it is a 2,1 or a 9.

    How to make it work for you:

    To match the number 25 (or 22, 52, and 55), you can use this character class:

    [25]{2}

    This will match a 2 digit number containing either 2 or 5 at either place.

提交回复
热议问题