简体   繁体   中英

The specified wildcard pattern is not valid: '*warnings: []*'

I'm trying to check if a text file contains a certain strings. All my strings are stored in a variable and I check the file the following way

ForEach ($word in ($words.split("|"))) {
  if ($word -ne "" -and $word -ne $null) {
    if ($textFile.toLower() -like '*'+$word.toLower()+'*') {
      $contains = $true
    }
  }
}

(Words is a string with different strings, with a | to seperate them).

This works perfectly, unless my string has [] in it. When my strings has [] in it, I will get the following error: (Example of words: Warnings: []|Errors: []|Failed to process path:|FilesWithError: 0|VerboseErrors: < It will go wrong on the first two words).

The specified wildcard pattern is not valid: *warnings: []*

You need to escape the metacharacters from the $word variable.

Here is a way to do it:

[Regex]::escape($word.toLower()).replace(']','\]')

I must call replace because the characters escaped by the static method [Regex]::escape is so minimal that doesn't include ] . Without this little help, the final regex would be invalid.

NOTE: I have tested this code on Powershell 2.0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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