我想匹配表格的日期
Monday May 26
我的尝试如下:
/(.*day Jan.*|Feb.*|Mar.*|Apr.*|May|Jun.*|Jul.*|Aug.*|Sep.*|Oct.*|Nov.*|Dec.* [1-31])/
UNIX和Perl中的regex形式似乎是相同的,所以这就是为什么我在这里问它。
Perl正则表达式和Perl兼容正则表达式与实用程序喜欢grep
实现的POSIX“基本”或“扩展”正则表达式略有不同。维基百科可能是了解差异的最佳场所。在Perl之外的其他地方也可以使用PCRE支持,例如GNU grep -P
。
对于基本的正则表达式:
echo "Monday Feb 23" | grep '^[[:alpha:]]+day (Jan\|Feb\|Mar\|Apr\|May\|Jun\|Jul\|Aug\|Sep\|Oct\|Nov\|Dec)[[:alpha:]]* [1-9][0-9]?$'
对于具有命名捕获组的Perl正则表达式:
$re = qr/
^ # Start of string
(?<day>[[:alpha:]]+day) # Match one or more alpha characters before "day".
\s+ # One or more whitespace chars
(?<month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[[:alpha:]]*) # Months
\s+ # One or more whitespace chars
(?<number>\d{1,2}) # 1-2 digits.
$ # End of string.
/x;
print "match\n" if ( "Thursday May 1" =~ $re );
print "match\n" if ( "Monday February 23" =~ $re );
print "no match\n" if ( "Wednesday May 123" !~ $re );
print "no match\n" if ( "Thursday Blarg 23" !~ $re );
print "no match\n" if ( "Inglebert January 5" !~ $re );
在x
该定界符后修改//
允许使用空格和意见,以便您的正则表达式是更具可读性。
成功的匹配会将每个字段存储在自己的捕获组中,可通过匹配哈希访问 $+
printf "day [%s] month [%s] day of month [%s]\n", $+{day}, $+{month}, $+{number}
如果您希望准确的话,可以使用数字匹配技术。
(?<number>[1-9]|[12][0-9]|3[01])
如果您要达到此级别,则应该考虑使用日期解析模块而不是正则表达式,因为日期太复杂了。例如,通常是4月31日或2月。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句