如何在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
执行此操作的正确方法是什么?
I want to split a string with multiple patterns:
ex.
my $string= "10:10:10, 12/1/2011";
my @string = split(/firstpattern/secondpattern/thirdpattern/, $string);
foreach(@string) {
print "$_\n";
}
I want to have an output of:
10
10
10
12
1
2011
What is the proper way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在正则表达式分隔符中使用 字符类 来匹配一组可能的字符分隔符。
说明
斜杠对
/.../
表示要匹配的正则表达式或模式。一对方括号
[...]
表示正则表达式的字符类。里面是可以匹配的可能字符集:冒号
:
、逗号,
、任何类型的空格字符\s
、和正斜杠\/
(使用反斜杠作为转义字符)。需要
+
来匹配其前面的 1 个或多个字符,在本例中是整个字符类。如果没有这个,逗号空格将被视为 2 个单独的分隔符,从而在结果中为您提供一个额外的空字符串。Use a character class in the regex delimiter to match on a set of possible delimiters.
Explanation
The pair of slashes
/.../
denotes the regular expression or pattern to be matched.The pair of square brackets
[...]
denotes the character class of the regex.Inside is the set of possible characters that can be matched: colons
:
, commas,
, any type of space character\s
, and forward slashes\/
(with the backslash as an escape character).The
+
is needed to match on 1 or more of the character immediately preceding it, which is the entire character class in this case. Without this, the comma-space would be considered as 2 separate delimiters, giving you an additional empty string in the result.错误的工具!
Wrong tool!
您可以按非数字进行拆分;
You can split on non-digits;
回答你原来的问题:
您正在寻找
|
运算符:但是,正如其他答案所指出的那样,您通常可以通过进一步简化或概括来改进这一点。
To answer your original question:
you were looking for the
|
operator:But, as the other answers point out, you can often improve on that with further simplifications or generalizations.
如果数字是您想要的,请提取数字:
不需要捕获括号,如
If numbers are what you want, extract numbers:
Capturing parentheses are not required, as specified in perlop:
当您解析明显是日期/时间的内容时,我想知道使用 DateTime::Format::Strptime 将其解析为 DateTime 对象。
As you're parsing something that is rather obviously a date/time, I wonder if it would make more sense to use DateTime::Format::Strptime to parse it into a DateTime object.