简体   繁体   English

正则表达式 - 替换在Powershell中

[英]Regex -replace in Powershell

I am trying to read a .sln file and extract the strings that contain the path to the .csproj within my solution. 我正在尝试读取.sln文件,并在我的解决方案中提取包含.csproj路径的字符串。

The lines that contain the information that I am looking for look like this: 包含我要查找的信息的行如下所示:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Project", "Project\Project.csproj", "{0DB516E6-4358-499D-BFBF-408F50A44E14}"

So, this is what I am trying: 所以,这就是我想要的:

$projectsInFile = Select-String "$slnFile" -pattern '^Project'
$csprojectsNames = $projectsInFile -replace ".+= `"(\S*) `""

Now, $csprojectsName contain the information that I am looking for, but also the rest of the string. 现在, $csprojectsName包含我要查找的信息,还包含字符串的其余部分。

Just like this: 像这样:

Project\Project.csproj", "{0DB516E6-4358-499D-BFBF-408F50A44E14}"

What is the best way to retrieve the name of the .csproj file without needing to manually cut the rest of the string? 检索.csproj文件名称的最佳方法是什么,而无需手动剪切其余字符串?

Thank you 谢谢

What you can do is capture the entire string and use a capture group in your replacement string thereby dropping the unneeded parts. 您可以做的是捕获整个字符串并在替换字符串中使用捕获组,从而删除不需要的部分。

$csprojectsNames = $projectsInFile -replace '.+= "(\S*) "(.*?)",.*"','$2'

The second capture group is the data inbetween the quotes that follow = "Project", "....." . 第二个捕获组是以下引号之间的数据= "Project", "....." Since it is the second capture group we replace the entire with that group '$2' . 由于它是第二个捕获组,我们用该组'$2'替换整个组。 Using single quotes ensure that PowerShell does not try to expand a variable. 使用单引号可确保PowerShell不会尝试扩展变量。

Better approach 更好的方法

You might just be able to use [^"]*?\\.csproj in select-string directly without having to do a secondary parse. That will match everything before .csproj that is not a quote so it wont gooble up too much. 你可能只能直接在select-string使用[^"]*?\\.csproj而无需进行二次解析。这将匹配.csproj之前的所有内容,这不是一个引用所以它不会过多。

You can use a group to capture the file path and then use the value of the group in as the replacement value. 您可以使用组捕获文件路径,然后使用组的值作为替换值。 For instance: 例如:

$csprojectsNames = $projectsInFile -replace 'Project\(.*?\) = "Project", "(.*?)"', '$1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM