[英]How to split a string with multiple patterns in perl?
我想拆分一個包含多個模式的字符串:
恩。
my $string= "10:10:10, 12/1/2011";
my @string = split(/firstpattern/secondpattern/thirdpattern/, $string);
foreach(@string) {
print "$_\n";
}
我希望得到一個輸出:
10
10
10
12
1
2011
這樣做的正確方法是什么?
使用正則表達式分隔符中的字符類來匹配一組可能的分隔符。
my $string= "10:10:10, 12/1/2011";
my @string = split /[:,\s\/]+/, $string;
foreach(@string) {
print "$_\n";
}
說明
斜線對/.../
表示要匹配的正則表達式或模式。
方括號[...]
表示正則表達式的字符類。
內是一組可匹配可能的字符:冒號:
,逗號,
任何類型的空格字符的\\s
,和斜杠\\/
(用反斜杠作為轉義字符)。
+
需要匹配緊接在其前面的一個或多個字符,在這種情況下是整個字符類。 如果沒有這個,逗號空間將被視為2個單獨的分隔符,在結果中為您提供一個額外的空字符串。
錯誤的工具!
my $string = "10:10:10, 12/1/2011";
my @fields = $string =~ /([0-9]+)/g;
你可以拆分非數字;
#!/usr/bin/perl
use strict;
use warnings;
use 5.014;
my $string= "10:10:10, 12/1/2011";
say for split /\D+/, $string;
如果您想要數字,請提取數字:
my @numbers = $string =~ /\d+/g;
say for @numbers;
如perlop所述 ,不需要捕獲括號:
/ g修飾符指定全局模式匹配 - 即在字符串中盡可能多地匹配。 它的行為取決於上下文。 在列表上下文中,它返回正則表達式中任何捕獲括號匹配的子字符串列表。 如果沒有括號,則返回所有匹配字符串的列表,就好像整個模式周圍有圓括號一樣。
my $string= "10:10:10, 12/1/2011";
my @string = split(m[(?:firstpattern|secondpattern|thirdpattern)+], $string);
my @string = split(m[(?:/| |,|:)+], $string);
print join "\n", @string;
當您正在解析顯然是日期/時間的事情時,我想知道使用DateTime :: Format :: Strptime將其解析為DateTime對象是否更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.