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?
A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter. split syntax is: Split /pattern/, variableName.
Below is the syntax of split function in perl are as follows. Split; (Split function is used to split a string.) Split (Split function is used to split a string into substring) /pattern/ (Pattern is used to split string into substring.)
split() method split the string by the occurrences of the regex pattern, returning a list containing the resulting substrings.
If you need to split a string into characters, you can do this: @array = split(//); After this statement executes, @array will be an array of characters. split recognizes the empty pattern as a request to make every character into a separate array element.
Use a character class in the regex delimiter to match on a set of possible delimiters.
my $string= "10:10:10, 12/1/2011";
my @string = split /[:,\s\/]+/, $string;
foreach(@string) {
print "$_\n";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With