Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with multiple patterns in perl?

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?

like image 541
quinekxi Avatar asked Nov 24 '11 05:11

quinekxi


People also ask

How do I split a string with multiple delimiters in Perl?

A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter. split syntax is: Split /pattern/, variableName.

How do I split a string into multiple strings in Perl?

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

How do you split a string by the occurrences of a regex pattern?

split() method split the string by the occurrences of the regex pattern, returning a list containing the resulting substrings.

How do I split a string into a character in Perl?

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.


1 Answers

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.

like image 171
stevenl Avatar answered Oct 07 '22 07:10

stevenl