【问题标题】:Checking if String contains another whole String检查字符串是否包含另一个完整的字符串
【发布时间】:2013-10-29 04:07:25
【问题描述】:

所以,我一直在尝试在线查找是否有办法让字符串在 java 中搜索另一个完整的字符串。不幸的是,我没有找到任何有效的方法。

我的意思是:

String str = "this is a test";

如果我搜索this is,它应该返回true。但如果我搜索this i,它应该是假的。

我尝试过使用String.matches(),但这不起作用,因为某些正在搜索的字符串中可能包含 [、]、? 等 - 这会使它被丢弃。使用 String.indexOf(search) != -1 也不起作用,因为它会为部分单词返回 true。

【问题讨论】:

    标签: java regex string


    【解决方案1】:

    在正则表达式中使用\b,零宽度字边界分隔符。

    String str = "this is a test";
    String search = "this is";
    Pattern p = Pattern.compile(String.format("\\b%s\\b", Pattern.quote(search)));
    boolean matches = p.matcher(Pattern.quote(str)).find();
    

    【讨论】:

    • 那行不通。使用 String.matches(".*?\\b" + search + "\\b*.?"); 不会得到像“[test]”这样的东西。
    • 肯定会的。你只需要先使用Pattern.quote(String)
    • 啊是的 - 应该使用 Matcher#find() 而不是 #matches()
    • 当搜索像String str = "[this] is...";这样的字符串时,当我搜索[this] is时它会返回false
    • 知道了——我要做的是p.matcher(Pattern.quote(str)).find(); 让它正确地找到其中的符号。
    【解决方案2】:

    如果您也将单词与非字母字符分开,而不仅仅是空格,您可以使用lookaround 机制。试试这样吧

    String str = "[this] is...";
    String search = "[this] is";
    
    Pattern p = Pattern.compile("(?!<\\p{IsAlphabetic})"
            + Pattern.quote(search) + "(?!\\p{IsAlphabetic})");
    boolean matches = p.matcher(str).find();
    

    它会检查匹配的部分之前或之后是否没有字母字符。

    注意:\\p{IsAlphabetic} 包括所有 Unicode 字母字符,例如 ż ź ć,而不仅仅是 a-z A-Z 范围。

    【讨论】:

    • 完全按照我需要的方式工作。谢谢!
    • @IAreKyleW00t 没问题 :)
    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多