我有一个从字符串中提取日期部分的用例,如下所示:
Job-2023-04-14.17.14.34
我需要输出为2023-04-14
。我尝试了下面的代码:
# Extract the date part from the string using a regular expression.
my $date = $string =~ /\d{4}-\d{2}-\d{2}/;
# Check if the date part is defined.
if (defined $date) {
# Print the date part.
print "$date\n";
} else {
# The date part is not defined.
print "The string does not contain a valid date.\n";
}
但是,它打印出 1。
最佳答案
使用capturing parentheses在正则表达式中,并在 $date
两边使用括号来强制列表上下文:
my ($date) = $string =~ /(\d{4}-\d{2}-\d{2})/;
输出:
2023-04-14
关于string - 使用正则表达式从字符串中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77261190/