如何使正则表达式字符类强制执行?

时间:2022-05-17 18:16:19

I'm trying to create a pattern. I have images and I want to select these images that contain the string "thumb" and I have the following pseudo structure:

我正在尝试创建一个模式。我有图像,我想选择包含字符串“拇指”的这些图像,我有以下伪结构:

something-$s[One of these digits: 1 or 2]thumb.jpg

I tried the following regex pattern:

我尝试了以下正则表达式模式:

$pattern_thumb = "/^.*-$s?[1-2]?\-thumb.jpg$/";

It selects these images correctly($s = 18054):

它正确选择这些图像($ s = 18054):

imagename-180541-thumb.jpg
imagename-180542-thumb.jpg

But the problem is, that it also selects images which don't have a 1 or 2 after the $s:

但问题是,它还会选择$ s后没有1或2的图像:

imagename-18054-thumb.jpg

How to add these digits [1-2] to be obligatory and not optional?

如何添加这些数字[1-2]是必须的而不是可选的?

1 个解决方案

#1


1  

You can use this pattern: /^.*-$s[12]\-thumb.jpg$/

你可以使用这种模式:/^.*-$s [12] \ --thumb.jpg $ /

  1. You only need 1 and 2 so there is no need to use range: [1-2] just [12]
  2. 你只需要1和2所以不需要使用范围:[1-2]只需[12]
  3. You need [12] be there as mandatory string, so you shouldn't use ?.
  4. 你需要[12]作为强制字符串,所以你不应该使用?

Check my regex 101 example and Repetition (PCRE regex syntax; PHP Manual).

检查我的正则表达式101示例和重复(PCRE正则表达式语法; PHP手册)。

#1


1  

You can use this pattern: /^.*-$s[12]\-thumb.jpg$/

你可以使用这种模式:/^.*-$s [12] \ --thumb.jpg $ /

  1. You only need 1 and 2 so there is no need to use range: [1-2] just [12]
  2. 你只需要1和2所以不需要使用范围:[1-2]只需[12]
  3. You need [12] be there as mandatory string, so you shouldn't use ?.
  4. 你需要[12]作为强制字符串,所以你不应该使用?

Check my regex 101 example and Repetition (PCRE regex syntax; PHP Manual).

检查我的正则表达式101示例和重复(PCRE正则表达式语法; PHP手册)。