string - 使用正则表达式从字符串中提取日期

标签 string datetime perl

我有一个从字符串中提取日期部分的用例,如下所示:

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

另请参阅:Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

关于string - 使用正则表达式从字符串中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77261190/

相关文章:

c# - DateTime 从 C# 到 MySQL : incomplete storage

json - 如何将 DBIx::Class::ResultSet 转换为 JSON

perl - 从哈希引用中获取值

c++ - 使用 vector 从c++中的文件中反转字符串

jQuery:在页面加载后的一秒钟内显示字符串的右侧部分

string - 如何在Spock框架中的功能方法名称中添加数字

perl - 如何在 Perl 中解决此警告

MySQL select string with\in it - 字符串是 IN () 的一部分

c# - 比较 Linq 中的 DateTime 对象

减法时的 Python timedelta 行为