Search code examples
powershellstring-matching

backtick in string to be searched in by powershell


So, I have an object with this content

some text
some more text 
INSERT INTO `myTable` VALUES
some text
some more text 

I want to select the line "INSERT INTO...". Notice the backticks. When I loop through the content of this particular lineI indeed see that this what is in it: [T][O][ ][`][m][y] ...

Now, when checking the following patterns:

$pattern1 = "INSERT INTO *"
$pattern2 = "INSERT INTO `*"
$pattern3 = "INSERT INTO ``*"
$pattern4 = "INSERT INTO `m*"
$pattern5 = 'INSERT INTO `*'
$pattern6 = 'INSERT INTO `r*'

$content | ForEach-Object {
    if ($_ -like $pattern1) {
        Write-Output "line '$_' corresponds with pattern"
    } 
    if ($_ -like $pattern2) {
        Write-Output "line '$_' corresponds with pattern"
    } 
    if ($_ -like $pattern3) {
        Write-Output "line '$_' corresponds with pattern"
    } 
    if ($_ -like $pattern4) {
        Write-Output "line '$_' corresponds with pattern"
    } 
    if ($_ -like $pattern5) {
        Write-Output "line '$_' corresponds with pattern"
    } 
    if ($_ -like $pattern6) {
        Write-Output "line '$_' corresponds with pattern"
    } 
}

I notice that only pattern 1 and 2 are "triggered" for the right line. This makes no sence for me. What am I missing? Or, more concretely, how can I validate that the entire sequence correcponds with the first line (so I also want to match the backticks )?


Solution

  • The backtick ` is the wildcard escaping character of the WildcardPattern class. If you want to match a literal backtick, the same needs to be escaped:

    'INSERT INTO `myTable` VALUES' -like 'INSERT INTO `m*'  # False
    'INSERT INTO `myTable` VALUES' -like 'INSERT INTO ``m*' # True
    

    Note the use of single-quotes in the examples above, this is so the backticks don't expand in the string.

    The following should also be an option:

    'INSERT INTO `myTable` VALUES' -like "$([WildcardPattern]::Escape('INSERT INTO `m'))*"
    

    However, there is an open issue about WildcardPattern.Escape not escaping lone backticks properly, please consider upvoting it so we might get this fixed in newer versions of PowerShell. See GitHub Issue #16306.

    You could use regex matching instead for this particular case:

    'INSERT INTO `myTable` VALUES' -match 'INSERT INTO `m.*' # True