【问题标题】:Splitting on whitespace character and strip empty fields拆分空白字符并去除空字段
【发布时间】:2013-09-26 15:07:04
【问题描述】:
($red, $tapinfo) = split(/:/, $line);
@fields = split(/\s+/, $tapinfo);

在数组字段中,我看到甚至添加了空间。我想消除空格,以便字段只包含非空格字符。请评论可能出了什么问题。

【问题讨论】:

  • 请显示您的输入。
  • 这对我很有效。
  • 你有前导空格吗?在' ' 上拆分将删除它,然后在\s+ 上拆分

标签: perl split whitespace


【解决方案1】:

我假设您在谈论剩余的前导空格,因此 @fields 看起来像:

$VAR1 = [
          '',    # empty field
          'foo',
          'bar'
        ];

这是因为您将 /\s+/ 用于您的 split,而您应该使用默认的 ' '(单个空格字符)。此默认行为将在拆分字符串之前去除前导空格。换句话说,你应该这样做:

@fields = split(' ', $tapinfo);

这记录在perldoc -f split:

As another special case, "split" emulates the default behavior
of the command line tool awk when the PATTERN is either omitted
or a *literal string* composed of a single space character (such
as ' ' or "\x20", but not e.g. "/ /"). In this case, any leading
whitespace in EXPR is removed before splitting occurs, and the
PATTERN is instead treated as if it were "/\s+/"; in particular,
this means that *any* contiguous whitespace (not just a single
space character) is used as a separator. However, this special
treatment can be avoided by specifying the pattern "/ /" instead
of the string " ", thereby allowing only a single space
character to be a separator.

【讨论】:

    【解决方案2】:

    split 的作用默认情况下与

    相同
    my @list = $string =~ /\S+/g;
    

    即它找到所有非空白字符的连续子字符串。

    您可以使用正则表达式,但要从split 获取默认行为,请将单个文字空格字符作为第一个参数传递。 不是正则表达式。文档是这样说的

    作为另一种特殊情况,split 模拟命令行工具 awk 的默认行为,当 PATTERN 被省略或由单个空格字符组成的文字字符串(例如 ' ' 或 "\x20" ,但不是例如 / /)。在这种情况下,EXPR 中的任何前导空格在拆分发生之前都会被删除,而 PATTERN 则被视为 /\s+/ ;特别是,这意味着任何连续的空格(不仅仅是单个空格字符)都被用作分隔符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多