为了匹配 2 个不连续的字母,您可以这样做(perl 中给出的示例,但它适用于理解 PCRE 的语言)
use strict;
use warnings;
use 5.010;
use YAPE::Regex::Explain;
my $re = qr/^\w+-(\w*?[a-z]+\w*?[a-z]+\w*?)-\d+\.html$/;
say YAPE::Regex::Explain->new( $re )->explain;
while(<DATA>) {
chomp;
say ($_ =~ $re ? "match : $_" : "not match : $_");
}
__DATA__
news-my_news_title_200_is-12345.html
news-m_200_s-12345.html
news-m_200-12345.html
输出:
match : news-my_news_title_200_is-12345.html
match : news-m_200_s-12345.html
not match : news-m_200-12345.html
正则表达式的解释:
(?-imsx:^\w+-(\w*?[a-z]+\w*?[a-z]+\w*?)-\d+\.html$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
- '-'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
\w*? word characters (a-z, A-Z, 0-9, _) (0 or
more times (matching the least amount
possible))
----------------------------------------------------------------------
[a-z]+ any character of: 'a' to 'z' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
\w*? word characters (a-z, A-Z, 0-9, _) (0 or
more times (matching the least amount
possible))
----------------------------------------------------------------------
[a-z]+ any character of: 'a' to 'z' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
\w*? word characters (a-z, A-Z, 0-9, _) (0 or
more times (matching the least amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
- '-'
----------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
html 'html'
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------