java - 正则表达式匹配器总是返回 false

标签 java android regex

我正在尝试解析这样的字符串;

/^/^this is a big|/*this is a bold text|/-this is strike through| i need the text between $/^ and $|

regexr 处测试了正则表达式和 java regex tester它们都显示了它的工作原理。

还引用: Java regex matcher always returns false Regex that always returns false

将我的代码与 Java Regex tutorial on Jenkov 进行比较而且看起来很相似

我的代码

 public static final String bold = "/\\/\\*(.*?)\\|/g";
    public static final String strike = "/\\/\\-(.*?)\\|/g";
    public static final String big = "/\\/\\^(.*?)\\|/g"; 


    String input = "/^/^this is a big|/*this is a bold text|/-this is strike through|";

    SpannableStringBuilder str = new SpannableStringBuilder(input.trim());
    Pattern pattern = big;
    Matcher matcher = pattern.matcher(str.toString());

            while (matcher.find()) {
                  str.setSpan(new RelativeSizeSpan((1.25f)),
                        matcher.start(), matcher.end(),
                        SPAN_INCLUSIVE_INCLUSIVE);
                //input.replace(matcher.group(1),"");
            }

所以 matcher.find() 返回 false,并且也没有任何 matcher.groups() 。 我真的不知道我在哪里出错了。

编辑

Pattern pattern = Pattern.compile(big);

我忘记添加该部分,因为正则表达式本身是另一个函数的返回,该函数返回已编译的模式。感谢您的所有帮助。

最佳答案

    Pattern pattern = Pattern.compile("/\\^(.*?)\\|");

    String input = "/^/^this is a big|/*this is a bold text|/-this is strike through|";
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        System.out.println("Found: " + matcher.group(1));
    }
    System.out.println("That’s all, folks");

输出是:

Found: /^this is a big
That’s all, folks

如果您想删除 /^| 之间的文本,请使用 Matcher.appendReplacement() 文档中给出的习惯用法:

    StringBuilder sb = new StringBuilder();
    while (matcher.find()) {
        matcher.appendReplacement(sb, "/^|");
    }
    matcher.appendTail(sb);
    System.out.println(sb.toString());  
/^|/*this is a bold text|/-this is strike through|

为什么你的代码不起作用?

仔细看看 Jenkov 教程。它有这样的代码行:

    String patternString = "is";

该模式不以 / 开头,也不以 /g 结尾。因此,通过包含这些部分,您需要将它们包含在匹配的文本中。由于它们不在您的输入字符串中,因此您的模式无法匹配。此外,您的代码中缺少对 Pattern.compile 的调用。它位于教程中的此代码行中:

    Pattern pattern = Pattern.compile(patternString);

链接: documentation of Matcher.appendReplacement()

关于java - 正则表达式匹配器总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721733/

相关文章:

java - super 和多问题

javascript - 使用Jsoup从网页获取数据返回空结果

android - Intent 启动 Activity 后会调用哪个方法?

regex - 我在 Linux 中使用带有正则表达式的 sed 但没有得到预期的答案

java - 从 @controller 读取 Spring 配置文件

java - 如何正确使用ChunkedStream

java - spring 是否有一个关闭过程来放置清理代码?

android - 抽屉导航打破布局

javascript - JavaScript 中用于 token 替换的正则表达式

javascript - 正则表达式匹配单词,除非它们前面有一个字符