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

2019-08-08 16:25发布

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?

3条回答
冷血范
2楼-- · 2019-08-08 17:06

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

($subname, $subtype) = split / (?!.*? )/, $heading, 2;
查看更多
Summer. ? 凉城
3楼-- · 2019-08-08 17:06

Assuming you know all the types:

($label, $type) = /(.*)\s*(min|avg|max)$/i;
查看更多
老娘就宠你
4楼-- · 2019-08-08 17:16

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

my ($label, $type) = /(.*)\s+(\S+)/;
查看更多
登录 后发表回答