【问题标题】:Pattern.compile() throws exceptionPattern.compile() 抛出异常
【发布时间】:2014-06-20 10:51:37
【问题描述】:

我正在使用正则表达式来查找书页中是否存在字符串。下面是相同的代码。

    String regex = ".*\\b.{0}" + searchText + ".{0}.*\\b";
    Pattern pattern = Pattern.compile(regex);
    pattern.matcher("This is the text area where I am trying to look for the particular text, which is in the variable searchText. This text will have the string (222M) as part of this string. The find method should give me a true result even if I don't enter the closing brakect of the word. This is a multiline string").find()

观察:

  • 案例 1:当 searchText = "(222M)" 时
  • 结果:找到字符串。

  • 案例 2:当 searchText = "(222M" // 括号丢失时

    我得到以下异常。

    索引 22 附近的正则表达式模式中的括号嵌套不正确: .\b.{0}(1110r.{0}.\b

还有更好的选择在页面中查找字符串。使用 String.contains() 不一致。这是在安卓平台上。 ^

【问题讨论】:

  • 请注意,您可以删除无用的.{0},因为它匹配一个空字符串。

标签: java android regex string pattern-matching


【解决方案1】:

尝试引用searchTextString

... + Pattern.quote(searchText) + ...

...因为它可能包含Pattern 保留字符,从而破坏了您的Pattern

Edit ...当它包含非闭合括号时就是这种情况。

编辑(二)

不太确定你想用Pattern".*\\b.{0}" 部分完成什么。

在这种情况下,这里有两个工作示例:

  • 用于文字匹配(String.contains 应该执行相同的操作)
  • 对于非单词限制匹配,其中给定String 之前或之后的任何字符都是非单词字符

    String searchText = "(222M";
    String regex = Pattern.quote(searchText);
    Pattern pattern = Pattern.compile(regex);
    Pattern boundedPattern = Pattern.compile("(?<=\\W)" + regex + "(?=\\W)");
    String input = "This is the text area where I am trying " +
        "to look for the particular text, which is in the variable searchText. " +
        "This text will have the string (222M) as part of this string. " +
        "The find method should give me a true result even if I don't " +
        "enter the closing brakect of the word. This is a multiline string";
    Matcher simple = pattern.matcher(input);
    Matcher bounded = boundedPattern.matcher(input);
    
    if (simple.find()) {
        System.out.println(simple.group());
    }
    if (bounded.find()) {
        System.out.println(bounded.group());
    }
    

输出

(222M
(222M

最后说明

如果您希望 Pattern(s) 不区分大小写,可以将 Pattern.CASE_INSENSITIVE 作为初始化标志添加到它们。

【讨论】:

  • 我已经尝试过 Pattern.quote(searchText),它会停止错误但与结果不匹配,因此无法达到目的。大小写为小写。感谢您对 {0} 的建议。
  • @Zooter 那么您的 Pattern 实际上与文本不匹配。您必须提供清晰的输入/输出示例 - 可能在一个新问题中。
  • 我已经编辑了这个问题。希望这有助于理解问题。
  • @Zooter 我看过你的例子。当然,使用您正在使用的Pattern,无法找到引用或未引用的“搜索文本”。如果您要查找的文本确实是searchText 的内容,我可以向您展示一个更简单的Pattern。否则你的第二个问题还不清楚。
  • 请帮我看看这个模式。我面临的问题是,当我搜索“(222M”时,我没有得到结果。引号仅表明searchText是一个字符串,因此您可以忽略它。感谢您的坚持并尝试提供帮助。
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 2011-05-30
  • 1970-01-01
  • 2011-02-25
  • 2012-01-24
  • 1970-01-01
相关资源
最近更新 更多