Perl: Is there a way to split on the last regex ma

2019-08-08 16:28发布

问题:

Here's an interesting problem. Is it possible to split a string on the last matching regex only?

Consider the following list of column headings from my data file (which read along the same line, being tab-separated):

Frequency Min
Frequency Avg
Frequency Max
Voltage L1 Min
Voltage L1 Avg
Voltage L1 Max
Active Power L1 Min
Active Power L1 Avg
Active Power L1 Max

At present, my data is appended as an array to each column (e.g. @{ $data{Frequency Min} }, @{ $data{Active Power L1 Avg} }). It would be nice to be able to create sub-hashes based on the Min, Max and Avg keywords (e.g. @{ $data{Frequency}{Min} }, @{ $data{Active Power L1}{Avg}), which is why I want to split on the last whitespace of each heading.

Notice that the situation is made more difficult by the fact that any number of whitespaces can occur before the final match is found.

I've thought of reversing the string, performing the split once and then re-reverse both strings separately, but that's too messy for my liking. Is there a neater way to do this?

回答1:

You can use a pure regex match rather than using split:

my ($label, $type) = /(.*)\s+(\S+)/;


回答2:

Split only on spaces that have no other space after them?

($subname, $subtype) = split / (?!.*? )/, $heading, 2;


回答3:

Assuming you know all the types:

($label, $type) = /(.*)\s*(min|avg|max)$/i;