I am trying to use regexr.com to write an expression to match some specific numbers in the filenames below. The expression will then be used in a PHP preg_match() method to identify files that should be on the server; unmatched files will be deleted.
我正在尝试使用regexr.com编写表达式以匹配下面文件名中的某些特定数字。然后,该表达式将用于PHP preg_match()方法,以识别应该在服务器上的文件;不匹配的文件将被删除。
In this example, I want the expression to match 187906 and 187909 (so the other files can be deleted). I figured I could write (187906|187909) which works, but of course that would also match 11879066 or 11879099 and so on. Before and after the number will always be a non-numeric character; either alphabetic or a full-stop.
在这个例子中,我希望表达式匹配187906和187909(因此可以删除其他文件)。我想我可以写(187906 | 187909)哪个有效,但当然也可以匹配11879066或11879099等等。数字之前和之后将始终是非数字字符;无论是字母还是全句。
-rw-r--r--. 1 root root 2190476 Jan 26 16:48 source187905.jpg
-rw-r--r--. 1 root root 1691755 Jan 26 16:48 source187906.jpg
-rw-r--r--. 1 root root 1780389 Jan 26 16:48 source187907.jpg
-rw-r--r--. 1 root root 1692330 Jan 26 16:48 source187908.jpg
-rw-r--r--. 1 root root 1622615 Jan 26 16:48 source187909.jpg
1 个解决方案
#1
2
Use lookarounds (?<!\d)
and (?!\d)
:
使用lookarounds(?
/(?<!\d)(?:187906|187909)(?!\d)/
See the regex demo.
请参阅正则表达式演示。
The (?<!\d)
negative lookbehind will fail the match if there is a digit before either of the two numbers and (?!\d)
negative lookahead will fail the match if there is a digit after either of the two numbers.
如果在两个数字中的任何一个之前有一个数字,则(?
Since that number looks to be at the end of the file name with a specific extension, you may even use
由于该数字看起来位于具有特定扩展名的文件名的末尾,您甚至可以使用
/(?<!\d)(?:187906|187909)\.jpg$/i
where \.jpg$
will match .jpg
at the end of the string ($
) and /i
modifier will make the pattern case insensitive.
其中\ .jpg $将匹配字符串末尾的.jpg($)和/ i修饰符将使模式不区分大小写。
#1
2
Use lookarounds (?<!\d)
and (?!\d)
:
使用lookarounds(?
/(?<!\d)(?:187906|187909)(?!\d)/
See the regex demo.
请参阅正则表达式演示。
The (?<!\d)
negative lookbehind will fail the match if there is a digit before either of the two numbers and (?!\d)
negative lookahead will fail the match if there is a digit after either of the two numbers.
如果在两个数字中的任何一个之前有一个数字,则(?
Since that number looks to be at the end of the file name with a specific extension, you may even use
由于该数字看起来位于具有特定扩展名的文件名的末尾,您甚至可以使用
/(?<!\d)(?:187906|187909)\.jpg$/i
where \.jpg$
will match .jpg
at the end of the string ($
) and /i
modifier will make the pattern case insensitive.
其中\ .jpg $将匹配字符串末尾的.jpg($)和/ i修饰符将使模式不区分大小写。