Perl:有没有办法在最后一次正则表达式匹配上分割? [英] Perl: Is there a way to split on the last regex match only?

查看:141
本文介绍了Perl:有没有办法在最后一次正则表达式匹配上分割?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有趣的问题。是否有可能在最后一个匹配的正则表达式上拆分字符串?



请考虑以下列表中的列标题(从同一行中读取) -

 频率最低
频率平均
频率最高
电压L1最低
电压L1平均
电压L1最大值
有功功率L1最小值
有功功率L1平均值
有功功率L1最大值

目前,我的数据作为数组附加到每列(例如 @ {$ data {Frequency Min}} @ {$ data {Active Power L1 Avg}} )。能够根据最小值,最大值和平均值关键字(例如 @ {$ data {Frequency} {Min}} @ {$ data {Active Power L1} {Avg} ),这就是为什么我想分割每个标题的最后一个空格。



请注意,在发现最终匹配之前可能会出现任意数量的空格,这让情况变得更加困难。



我想到反转字符串,执行一次分割,然后分别重新反转两个字符串,但这太麻烦了,我不喜欢。有没有更好的方法可以做到这一点?

可以使用纯正则表达式匹配,而不是使用 ($ label,$ type)= /(.*)\s+分开

  my (\S +)/; 


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?

解决方案

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

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

这篇关于Perl:有没有办法在最后一次正则表达式匹配上分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆