Powershell 正则表达式获取字符串的一部分 [英] Powershell Regex expression to get part of a string

查看:145
本文介绍了Powershell 正则表达式获取字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取出一个字符串的一部分以在其他地方使用它.例如,我有以下字符串:

I would like to take part of a string to use it elsewhere. For example, I have the following strings:

  • 项目 XYZ 是项目名称 - 20-12-11

我想获取值XYZ 是项目名称";从字符串.项目"二字和字符-"在号码永远存在之前.

I would like to get the value "XYZ is the project name" from the string. The word "Project" and character "-" before the number will always be there.

推荐答案

我认为 lookaround 正则表达式在这里可以工作,因为Project"和-"一直都在:

I think a lookaround regular expression would work here since "Project" and "-" are always there:

(?<=Project ).+?(?= -)

环视对于处理获取子字符串的情况很有用.

A lookaround can be useful for cases that deal with getting a sub string.

说明:

  • (?<= = 负向后视
  • 项目 = 起始字符串(包括空格)
  • ) = 关闭负向后视
  • .+? = 匹配介于两者之间的任何内容
  • (?= = 正向预测
  • - = 结束字符串
  • ) = 关闭正向预测
  • (?<= = negative lookbehind
  • Project = starting string (including space)
  • ) = closing negative lookbehind
  • .+? = matches anything in between
  • (?= = positive lookahead
  • - = ending string
  • ) = closing positive lookahead

PowerShell 中的示例:

Example in PowerShell:

Function GetProjectName($InputString) {
    $regExResult = $InputString | Select-String -Pattern '(?<=Project ).+?(?= -)'
    $regExResult.Matches[0].Value
}

$projectName = GetProjectName -InputString "Project XYZ is the project name - 20-12-11"
Write-Host "Result = '$($projectName)'"

这篇关于Powershell 正则表达式获取字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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