Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - PowerShell -match vs -like

Reading official docs it's obvious that PowerShell -match operator is more powerful than -like (due to regular expressions). Secondly, it seems ~10 times faster according to this article https://www.pluralsight.com/blog/software-development/powershell-operators-like-match.

Are there specific cases when I should prefer -like instead of -match? If there not, why at all should I use -like? Does it exist because of historical reasons?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...