I want to adapt a html string with a PowerShell script. The URL to a cascading style sheet shall be replace to a local CSS file. I use this replace command with a regular expression. But the result is not as expected.
$a = '<link rel="stylesheet" type="text/css" href="https:/my.web.site/c5fb04c9-44e6-40d1-bb1f-46b170a9e53f" id="style-standard" />'
$b = $a.Replace('href="(.*?)", '$1.css')
The attributes of the LINK item can occur in any order.
How can I fix the search expression so, that the parentheses capure the GUID in the input?
CodePudding user response:
If I understood correctly, you're looking for this as a result:
<link rel="stylesheet" type="text/css" href="c5fb04c9-44e6-40d1-bb1f-46b170a9e53f.css" id="style-standard" />
If that's the case, the following regex replacement should work. See https://regex101.com/r/hSy1qm/1 for more info.
$a = '<link rel="stylesheet" type="text/css" href="https:/my.web.site/c5fb04c9-44e6-40d1-bb1f-46b170a9e53f" id="style-standard" />'
$a -replace '(?<=href=").*(?<guid>[\w\d]{8}-([\w\d]{4}-){3}[\w\d]{12}).*?(?=")', '${guid}.css'
Worth noting that the .Replace()
string method is not regex compatible, for replacement using regex you can use the -replace
operator.
If you want to test first if the string has a GUID, you can have a condition using the -match
operator and the automatic variable $Matches
:
$a = '<link rel="stylesheet" type="text/css" href="https:/my.web.site/c5fb04c9-44e6-40d1-bb1f-46b170a9e53f" id="style-standard" />'
$re = '(?<=href=").*(?<guid>[\w\d]{8}-([\w\d]{4}-){3}[\w\d]{12}).*?(?=")'
if($a -match $re) {
$a -replace $Matches[0], "$($Matches['guid']).css"
}
CodePudding user response:
With -replace instead of .replace():
$a = '<link rel="stylesheet" type="text/css" href="https:/my.web.site/c5fb04c9-44e6-40d1-bb1f-46b170a9e53f" id="style-standard" />'
$a -Replace 'href="(.*?)"', '$1.css'
<link rel="stylesheet" type="text/css" https:/my.web.site/c5fb04c9-44e6-40d1-bb1f-46b170a9e53f.css id="style-standard" />