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?
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.