java - Matcher.Find() 在应该为 true 时返回 false

标签 java regex

        String s = "test";
        Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
        Matcher matcher = pattern.matcher(searchableText);
        boolean topicTitleFound = matcher.find();
        startIndex = 0;
        while (topicTitleFound) {
            int i = searchableText.indexOf(matcher.group(0));
            if (i > startIndex) {
                builder.append(documentText.substring(startIndex, i - 1));
        ...

这是我所理解的文字:

Some text comes here

topicTitle test :
test1 : testing123
test2 : testing456
test3 : testing789
test4 : testing9097

当我在 http://regexpal.com/http://www.regexplanet.com 上测试这个正则表达式时,我清楚地发现标题是:“topicTitle test”。但在我的 java 代码中 topicTitleFound 返回 false。

请帮忙

最佳答案

searchableText< 中的换行符 ('\n') 之前可能有回车符 ('\r')/。这将导致匹配在行边界处失败。

为了使您的多线模式更加强大,请尝试使用 MULTILINE编译正则表达式时的选项。然后根据需要使用 ^$ 来匹配行边界。

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
<小时/>

更新:

实际测试您的代码后,我发现无论回车符是否存在,该模式都匹配。换句话说,您的代码按原样“工作”,并且首次分配时(在 while 循环之外),topicTitleFoundtrue

您确定 topicTitleFound 的结果为 false 吗?或者问题出在循环中?

顺便说一句,使用 indexOf() 既浪费又尴尬,因为匹配器已经存储了组 0 开始的索引。改用这个:

int i = matcher.start(0);

关于java - Matcher.Find() 在应该为 true 时返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637377/

相关文章:

Java - Jtable 颜色

java - 为什么 SerialVersionUID 是静态的

mysql - 如何将日志文件的每一行拆分为 SQL 列? (也许使用正则表达式进行分割)

Java Regex 接受限定符中的任何内容

Java:找出对象的所有数字字段是否为 0

java - 错误查找对象 Spring JPA : "Error accessing field by reflection for persistent property"

java - 使用 Alpakka 连接器的多个消费者线程

使用多个定界符拆分的 Java 字符串

python - 正则表达式更改搜索字符串中的位置

javascript - 检查自由代码营中的回文(不需要解决方案)