除非在单引号字符串内,否则如何按空格拆分字符串? [英] How can I split a string by whitespace unless inside of a single quoted string?

查看:43
本文介绍了除非在单引号字符串内,否则如何按空格拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种拆分包含以下格式文本的字符串的解决方案:

I'm seeking a solution to splitting a string which contains text in the following format:

"abcd efgh 'ijklm no pqrs' tuv"

将产生以下结果:

['abcd', 'efgh', 'ijklm no pqrs', 'tuv']

换句话说,除非在单引号字符串内,否则它会按空格拆分.我认为它可以通过使用Lookaround"运算符,特别是平衡运算符的 .NET regexp 来完成.我对 Perl 不太确定.

In other words, it splits by whitespace unless inside of a single quoted string. I think it could be done with .NET regexps using "Lookaround" operators, particularly balancing operators. I'm not so sure about Perl.

推荐答案

使用 Text::ParseWords:

#!/usr/bin/perl

use strict; use warnings;
use Text::ParseWords;

my @words = parse_line('\s+', 0, "abcd efgh 'ijklm no pqrs' tuv");

use Data::Dumper;
print Dumper \@words;

输出:

C:\Temp> ff
$VAR1 = [
          'abcd',
          'efgh',
          'ijklm no pqrs',
          'tuv'
        ];

您可以查看 Text::ParseWords::parse_line 的源代码以了解使用的模式.

You can look at the source code for Text::ParseWords::parse_line to see the pattern used.

这篇关于除非在单引号字符串内,否则如何按空格拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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