且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl 中的模式匹配是如何工作的?

更新时间:2023-02-20 22:13:53

来自 docs一个>:

默认情况下,量化的子模式是贪婪的",也就是说,它会尽可能多地匹配(给定一个特定的起始位置),同时仍然允许模式的其余部分匹配

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match

所以,首先 (.*) 会尽可能多.

So, first (.*) will take as much as possible.

简单的解决方法是使用非贪婪量词:*?.或者不匹配每个字符,但匹配除逗号之外的所有字符:([^,]*).

Simple workaround is using non-greedy quantifier: *?. Or match not every character, but all except comma: ([^,]*).