【问题标题】:Java matcher does not find match, even though the regex works separately即使正则表达式单独工作,Java 匹配器也找不到匹配项
【发布时间】:2015-04-12 07:32:44
【问题描述】:

我正在尝试获取给定字符串的“预告片”并将其作为值放入 HashMap。 'teaser' 我的意思是一个子字符串(最大长度 50 个字符)结束一个单词边界。

这是一个代码示例,展示了我是如何尝试这样做的:

import java.util.regex.*;             

public class Test {                    
  public static void main(String[] args) throws Exception {
    final Pattern pattern = Pattern.compile("(^.{0,50}\b)"); 
    final Matcher m = pattern.matcher(
        "This is a long string that I want to find a shorter teaser for."); 
    if (m.find()) {
      System.out.println("Found: " + m.group(1)); 
    } else {  
      System.out.println("No match");   
    }                                                          
  }             
}    

我希望它会打印出来:

Found: This is a long string that I want to find a

但它会打印:

No match

如果我单独测试这个正则表达式,它会做它应该做的 - 它找到一个最大长度为 50 个字符并在单词边界上结束的值子字符串。但是如果我调试它,m.find 总是给我一个错误。

任何想法如何解决这个问题? (我专注于获取预告片,而不是使用 Matcher.find() ;-))

【问题讨论】:

  • 使用:Pattern.compile("(^.{0,50}\\b)")
  • 按照 Anubhava 所说,在循环之外声明您的 pattern.compile。您不必每次都创建它们。
  • 也感谢这个。。从所有循环中得到它。

标签: java regex find matcher


【解决方案1】:

根据Oracle documentation on Characters \b 是字符串中退格的转义序列。但是,您想要 \b 单词边界的正则表达式,因此您需要将斜杠更改为文字斜杠,即 \\ 以便 Pattern.compile 看到 \b

Pattern.compile("(^.{0,50}\\b)")

您可以通过在字符串上调用 .toCharArray() 来查看此效果

单斜线

System.out.println(Arrays.toString("\b".toCharArray()));
=> []

双斜线

System.out.println(Arrays.toString("\\b".toCharArray()));
=> [\, b]

【讨论】:

  • 天啊!非常感谢,第二个斜线不见了。现在工作得很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
相关资源
最近更新 更多