PowerShell -match vs -like

前端 未结 3 1211
萌比男神i
萌比男神i 2020-12-21 08:41

Reading official docs it\'s obvious that PowerShell -match operator is more powerful than -like (due to regular expressions). Secondly, it seems ~1

相关标签:
3条回答
  • 2020-12-21 09:20

    I've never seen -match test that much faster than -like, if at all. Normally I see -like at about the same or better speed.

    But I never rely on one test instance, I usually run through about 10K reps of each.

    If your're looking for performance, always prefer string methods if they'll meet the requirements:

    $string = '123abc'    
    
    (measure-command {
    for ($i=0;$i -lt 1e5;$i++)
     {$string.contains('3ab')}
    }).totalmilliseconds
    
    (measure-command {
    for ($i=0;$i -lt 1e5;$i++)
     {$string -like '*3ab*'}
    }).totalmilliseconds
    
    (measure-command {
    for ($i=0;$i -lt 1e5;$i++)
     {$string -match '3ab'}
    }).totalmilliseconds
    
    265.3494
    586.424
    646.4878
    
    0 讨论(0)
  • 2020-12-21 09:38

    See this explanation from Differences Between -Like and -Match

    In a nutshell, if you are thinking, 'I am probably going to need a wildcard to find this item', then start with -Like. However, if you are pretty sure of most of the letters in the word that you are looking for, then you are better off experimenting with -Match.

    Here is a more technical distinction: -Match is a regular expression, whereas -Like is just a wildcard comparison, a subset of -Match.

    So, whenever you are not sure what character classes, i.e. digits, letters, punctuation, etc., can there be inside, when you just want to match any character, you should be using -Like with its wildcards.

    When you know there must be a digit at the start followed with 1+ sequences of a colon followed with alphanumeric characters up to the end of the string, use -Match with its powerful regular expressions.

    0 讨论(0)
  • 2020-12-21 09:38

    You should prefer -like when your comparator string is a dos-style filename wildcard. If you have a cmdlet that is designed to look like a "standard" windows command line application, then you can expect file name parameters to include dos-style wildcards.

    You might have a grep-like cmdlet that takes a regex and a list of files. I can imagine it being used like this:

    > yourMagicGrepper "^Pa(tt).*rn" *.txt file.*
    

    You would use -match when working with the first parameter, and -like for all other parameters.

    In other words: it depends on your functional requirements.

    0 讨论(0)
提交回复
热议问题