代码之家  ›  专栏  ›  技术社区  ›  webnoob

当字符串包含s时,正则表达式在不在parethesis中的空格上拆分字符串

  •  0
  • webnoob  · 技术社区  · 7 年前

    序曲

    我正在尝试执行一个操作,该操作要求我解析特定文件中的每个单词。最直接的方法是使用以下命令加载文本:

    $content = Get-Content -Path .\<filename>
    

    然后,我将把每个单词分成一行(这允许我非常快速地进行单词计数和单字搜索)。问题是当我使用这行代码时:

    $content.split("\s+")
    

    它应该在每个(一个或多个)空白字符上创建一个新行(拆分)。不幸的是,我的结果如下所示:

    $content.split("\s+")
    The SpeechSynthe
    izer cla
    
    provide
    acce
    
     to the functionality of a 
    peech 
    ynthe
     i
      engine that i
      in
    talled on the ho
    t computer. In
    talled 
    peech 
    ynthe
     i
     engine
    

    但是当我跑的时候

    $content -split("\s+")
    

    结果将正确显示:

    $content -split("\s+")
    The
    SpeechSynthesizer
    class
    provides
    access
    to
    the
    functionality
    of
    a
    speech
    synthesis
    

    使用powershell V.4时,我无法理解执行该操作之间的区别。

    $content.split(“\s+”)

    和

    是以及为什么他们会输出不同的结果。

    这个功能刚刚坏了吗?

    0 回复  |  直到 11 年前
        1
  •  3
  •   Wiktor Stribiżew    11 年前

    Powershelladmin wiki :

    这个 -split "\s+" .

    和

    要拆分单个或多个字符,还可以使用 System.String 对象方法 Split() .

    PS C:\> 'a,b;c,d'.Split(',') -join ' | '
    a | b;c | d
    PS C:\> 'a,b;c,d'.Split(',;') -join ' | '
    a | b | c | d

    所以,您只是传递了需要拆分的符号 $content.split("\s+")

    在里面 $content -split("\s+") , \s+ 是正则表达式模式匹配 1个或多个空白符号 .