Volodymyr Nabok
Volodymyr Nabok

Reputation: 473

Compare RegExp-string with special characters in PowerShell

it is needed to compare $string1 to certain string-template in PowerShell

PS C:\ $string1 = '\\<a href="main\\.php\\?act=forum\\&hdl=read_\\&id=(\d+)\\&pid=313" class="small_name2"\\>Learn the powershell tool\\</a\\>'
PS C:\ $string1 -match '<a href="main.php?act=forum&hdl=read_&id=83523&pid=313" class="small_name2">Learn the powershell tool</a>'
False

What is wrong in templates and maybe string above? Thank you!

Upvotes: 1

Views: 1133

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200413

The -match operator is not commutative, so you can't switch the operands. First operand must be the string you want to match against a regular expression, second operand must be the regular expression. Also, the double backslashes in your regular expression evaluate to literal backslashes instead of escaping special characters.

Change this:

$string1 = '\\<a href="main\\.php\\?act=forum\\&hdl=read_\\&id=(\d+)\\&pid=313" class="small_name2"\\>Learn the powershell tool\\</a\\>'
$string1 -match '<a href="main.php?act=forum&hdl=read_&id=83523&pid=313" class="small_name2">Learn the powershell tool</a>'

into this:

$string1 = '\<a href="main\.php\?act=forum\&hdl=read_\&id=(\d+)\&pid=313" class="small_name2"\>Learn the powershell tool\</a\>'
'<a href="main.php?act=forum&hdl=read_&id=83523&pid=313" class="small_name2">Learn the powershell tool</a>' -match $string1

Upvotes: 2

Related Questions