- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我注意到调用 Matcher.lookingAt()
会影响 Matcher.find()
。我在我的代码中运行了 lookingAt()
,它返回了 true。然后,当我运行 find()
以便开始返回匹配项时,我得到了 false。如果我删除 lookingAt()
调用,find()
返回 true 并打印我的匹配项。有谁知道为什么?
试验1:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
System.out.println(matches.lookingAt()); //after running this, find() will return false
while (matches.find())
System.out.println(matches.group());
//Output: true
试验 2:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
//System.out.println(matches.lookingAt()); //without this, find() will return true
while (matches.find())
System.out.println(matches.group());
//Output: T234
试验 3:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
while (matches.lookingAt())
System.out.println(matches.group());
//Output: T234 T234 T234 T234 ... till crash
//I understand why this happens. It's not my question but I just included it in case someone may try to suggest it
最终,我想要实现的是:首先确认匹配在字符串的开头,然后打印出来。我最终做了:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if(matches.lookingAt())
System.out.println(matches.group());
//Output: T234
这解决了我的问题,但我的问题是:有谁知道为什么 lookingAt()
会影响 find()
?
最佳答案
在试验 1 中,调用 lookingAt
匹配 T234
,随后调用 find
开始在 处寻找匹配项上一场比赛结束。如果你想回到字符串的开头,你需要调用 Matcher.reset()
. Matcher.find() 的文档中对此进行了解释:
This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
请注意,lookingAt
与 start
、end
和 group
的工作方式与 find
确实如此,所以如果您只对字符串的开头感兴趣,您可以这样做:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if (matches.lookingAt())
System.out.println(matches.group());
你必须在这里使用 if
而不是 while
,因为 lookingAt
总是从字符串的开头而不是结尾开始查找上一场比赛的结果,所以 while
会一直循环下去。
关于java - 为什么 Matcher.find() 在 Matcher.lookingAt() 之后运行时返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12625171/
我使用 Matcher 实例通过 lookingAt() 方法在某些输入的开头匹配模式。然而,当我从空字符串创建 Pattern 并尝试将其与非空(修剪过的)字符串匹配时,lookingAt() 返回
我正在看 Java 正则表达式教程,标题本身就很清楚了。看起来 Matcher.lookingAt() 正在尝试匹配整个字符串。是真的吗? 最佳答案 documentation for Matcher
Java 有一个名为“LookingAt()”的正则表达式函数,它允许对模式进行部分匹配,我的问题是: .net 是否有等同于“LookingAt()”的东西? 我可能会也可能不会将其用于 KeyPr
我正在将一个框架从 Java 移植到 Objective C,它在很大程度上依赖于正则表达式。不幸的是,Java 正则表达式 API 与 Objective C API 有很大不同。 我正在尝试使用
我注意到调用 Matcher.lookingAt() 会影响 Matcher.find()。我在我的代码中运行了 lookingAt(),它返回了 true。然后,当我运行 find() 以便开始返回
我正在寻找一种方法来确定单个正则表达式是否匹配整个字符串、字符串的开头或 C# 中的一部分。 在 Java 中,您可以构造一个 Matcher 对象,并使用方法 matches() 来检查它是否与整个
我开始使用正则表达式进行环视 我认为正则表达式是 q 后跟 u 的正前瞻。但是当输入字符串是“qu”时,它不匹配。但是我得到了 lookingAt 函数的真实结果。 String regex="q(?
我是一名优秀的程序员,十分优秀!