gpt4 book ai didi

java - 为什么我的正则表达式是贪婪的?

转载 作者:行者123 更新时间:2023-12-01 18:12:32 25 4
gpt4 key购买 nike

  1. alsjasdfadasdfasfasfa

2.asdfasdfasdf

3.

2.

上面是我尝试与此正则表达式匹配的字符串 - \n1.(.+)\n2.所以,我想做的是匹配 1。和下一个 2。但我的正则表达式仍然匹配最后 2 个。我使用“单行”修饰符,即,点匹配此正则表达式上的所有内容。我做错了什么?

最佳答案

(.+) 更改为 (.+?)Pattern 的 JavaDoc 对此进行了介绍。 “勉强量词”下的类。

如果我们看一下official tutorial我们可以在“贪婪量词、不情愿量词和占有量词之间的差异”中阅读更多相关内容。

The reluctant quantifiers, however, take the opposite approach: They start at the beginning of the input string, then reluctantly eat one character at a time looking for a match. The last thing they try is the entire input string.

关于java - 为什么我的正则表达式是贪婪的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31902674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com