如何用Ruby的scan方法和正则提取磁盘路径与使用率百分比
问题原因
你现有代码的问题出在两处:
- 正则中使用贪婪匹配
.*,会从字符串中第一个[开始,一直匹配到最后一个]之前的内容,导致多个路径条目被合并成一个匹配结果 - 提前将所有逗号替换为空的操作,会让
percent full后的数值和下一个条目的开头拼接在一起,你原本用[^[:space:]]+匹配数值的逻辑会抓取到多余内容
解决代码
不需要提前修改原字符串,直接使用如下正则即可提取所有对应条目:
test = "Disk/File System/[/dev/mapper/rhel-var (/var)]/MB free=14791, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB free=9451, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/percent full=1.0, Disk/File System/[/dev/sda2 (/boot)]/MB total=1974, Disk/File System/[/dev/mapper/rhel-home (/home)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/percent full=61.0, Disk/File System/[/dev/mapper/rhel-var (/var)]/percent full=23.0, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB total=452543, Disk/File System/[/dev/mapper/rhel-opt (/opt)]/MB free=426145, Disk/File System/[/dev/mapper/rhel-root (/)]/MB total=10015, Disk/File System/[/dev/mapper/rhel-root (/)]/MB free=3717, Disk/File System/[/dev/mapper/rhel-var (/var)]/MB total=20030, Disk/File System/[/dev/sda2 (/boot)]/percent full=9.0, Disk/File System/[/dev/sda2 (/boot)]/MB free=1699, Disk/File System/[/dev/mapper/rhel-home (/home)]/percent full=1.0, Disk/File System/[devtmpfs (/dev)]/MB total=3851, Disk/File System/[devtmpfs (/dev)]/percent full=0.0, Disk/File System/[devtmpfs (/dev)]/MB free=3851" result = test.scan(%r{Disk/File System/\[([^\]]+)\]/percent full=([\d.]+)}) p result
正则说明
- 使用
%r{}作为Ruby正则字面量写法,避免频繁转义路径中的/字符 \[([^\]]+)\]:匹配方括号包裹的路径,[^\]]+表示匹配所有非]的字符,刚好完整提取路径内容,不存在贪婪匹配问题percent full=([\d.]+):匹配使用率数值,[\d.]+仅匹配数字和小数点,遇到逗号、空格等其他字符自动停止,无需提前处理原字符串
运行结果
输出为每个元素是[路径, 使用率]的二维数组:
[ ["/dev/mapper/rhel-opt (/opt)", "1.0"], ["/dev/mapper/rhel-root (/)", "61.0"], ["/dev/mapper/rhel-var (/var)", "23.0"], ["/dev/sda2 (/boot)", "9.0"], ["/dev/mapper/rhel-home (/home)", "1.0"], ["devtmpfs (/dev)", "0.0"] ]
内容的提问来源于stack exchange,提问作者Syirtblplmj
相关产品推荐
相关产品推荐

