【问题标题】:String split in windows powershellwindows powershell中的字符串拆分
【发布时间】:2020-02-07 01:39:23
【问题描述】:

能否请您帮我获得所需的输出,其中 SIT 是环境,文件类型是属性,我需要删除环境和字符串的扩展名。

#$string="<ENV>.<can have multiple period>.properties
*$string ="SIT.com.local.test.stack.properties"
$b=$string.split('.')
$b[0].Substring(1)*

必需的输出:com.local.test.stack //可以有多个句点

【问题讨论】:

    标签: regex powershell split


    【解决方案1】:

    应该这样做。

    $string = "SIT.com.local.test.stack.properties"
    
    # capture anything up to the first period, and in between first and last period
    if($string -match '^(.+?)\.(.+)\.properties$') {
        $environment = $Matches[1]
        $properties = $Matches[2]
    
        # ... 
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用

      $string -replace '^[^.]+\.|\.[^.]+$'
      

      这将删除除点之外的前 1+ 个字符,然后是一个点,最后一个点后跟任何 1+ 个非点字符。

      查看regex demoregex graph

      详情

      • ^ - 字符串开头
      • [^.]+ - 除了. 之外的 1+ 个字符
      • \. - 一个点
      • | - 或
      • \. - 一个点
      • [^.]+ - 除. 之外的 1+ 个字符
      • $ - 字符串结束。

      【讨论】:

        【解决方案3】:

        您可以使用 -match 使用正则表达式捕获所需的输出

        $string ="SIT.com.local.test.stack.properties"
        $string -match "^.*?\.(.+)\.[^.]+$"
        $Matches.1
        

        【讨论】:

        • 谢谢@r007ed 和 mtnielsen,两个答案都有效
        【解决方案4】:

        您也可以使用 Split 运算符来做到这一点。

        ($string -split "\.",2)[1]
        

        说明:

        您使用正则表达式 \. 拆分文字 . 字符。 ,2 语法告诉 PowerShell 在拆分后返回 2 个子字符串。 [1] 索引选择返回数组的第二个元素。 [0] 是第一个子字符串(在本例中为SIT)。

        【讨论】:

          猜你喜欢
          • 2019-12-16
          • 1970-01-01
          • 2013-09-26
          • 1970-01-01
          • 1970-01-01
          • 2014-07-27
          • 1970-01-01
          • 2016-09-04
          • 2015-02-07
          相关资源
          最近更新 更多