简体   繁体   中英

Regular Expression - is .*$ the same as .*

I am cleaning up another person's regular expressions and they currently end all of theirs with

.*$

So wouldn't the following be exactly the same?

.*

.* will match as much as it can, but by default . doesn't match newlines. If the text you're matching against has newlines and you're in MULTILINE but not DOTALL mode, then .*$ might not match where .* does. Without newlines (or if you're not in MULTILINE) or if you've set DOTALL, they're identical since * is a greedy operator and will match as much as it can.

In the end though, the exact answer depends on the regular expression engine. So your results may differ.

并非总是如此,它取决于正在使用的设置,大多数正则表达式引擎都具有“多线”模式,如果启用它们,它们的行为将有所不同。

$ asserts that the match reaches the end of the string, which will always happen since . matches anything. So, yes, they are the same.

However, as Paul Creasey pointed out, there are times when they aren't the same. When multiline is enabled, $ will match the end of the multi-line string. But, unless dot-all (meaning "dot" matches all) is also enabled, . can't match newlines.

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