regex - 将字符串拆分为哈希
问题描述
我有一些这样的日志消息:
foo=value bar="some other value" complex.key="something more \"complex\""
将这样的字符串拆分为相应的哈希的最简单方法是什么?
在这种情况下,预期的输出将是:
{
'foo' => 'value',
'bar' => 'some other value',
'complex.key' => 'something more "complex"'
}
解决方案
这就是Text::ParseWords的用途。
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Text::ParseWords;
use Data::Dumper;
my $in = 'foo=value bar="some other value" complex.key="something more \"complex\""';
my %hash = parse_line('[= ]', 0, $in);
say Dumper \%hash;
输出:
$VAR1 = {
'complex.key' => 'something more "complex"',
'foo' => 'value',
'bar' => 'some other value'
};
聪明之处都发生在parse_line()
。它的三个参数是:
- 定义输入字符串中字段分隔符的正则表达式(此处为空格或“=”)
- 指示是否要在字符串周围保留引号的标志
- 你的输入字符串
推荐阅读
- python - Scikit-Learn Pipeline ValueError: Input contains NaN, infinity or a value too large for dtype('float64') whenfitting model
- c++ - 如何获取函数模板以匹配类型?
- python - 如何在不使用列表或任何其他数据结构的情况下打印最小和最大数量的 n 个随机数
- python - 展开一个图,使得每个节点对最多连接一次
- java - 从 spring webflux 反应管道中提取变量
- monaco-editor - 如何在 Monaco 编辑器中使用 HTML 和 JS/CSS
- linux - 通过命令行启动时,自包含的 asp.net 核心应用程序运行良好,但是当在 linux 下作为服务启动时,它会立即崩溃
- powershell - WinSCP - 未知命令和“.log”未被识别为内部或外部命令
- flutter - 参数 'pageController' 的值不能为 'null',因为它的类型,但隐含的默认值是 'null'
- sql - 使用此查询查找百分比