【问题标题】:String.contains(searchText) doesn't work for more than one wordString.contains(searchText) 对多个单词不起作用
【发布时间】:2014-08-15 15:46:57
【问题描述】:

我有一些内容,我正在尝试查找内容中是否存在某些“searchText”。当我在“searchText”中查找单个单词时,String.contains(searchText) 返回 true,但对于不止一项工作返回 false。下面是显示实现的 sn-p。我需要确定内容中是否存在 searchText。

    boolean found;
    String searchText = "particular text";
    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";
    if(input.contains(searchText)) {
        found = true;
    }

我需要使用正则表达式吗? 让我指出我之前没有提到的研究和我的尝试。

我已经尝试过下面的正则表达式

pattern = Pattern.compile("(?<=\\W)" + searchText + "(?=\\W)");

这也不起作用。

注意:这是在 Android 上。

【问题讨论】:

  • 对于您给出的情况,返回 true,因为字符串包含“特定文本”。换句话说,您已经给出了一个已经有效的示例 - 请给我们一个您期望有效但没有有效的示例。
  • 这行得通。此外,找到 = input.contains(searchText)
  • 你的代码返回真!
  • 这是行不通的代码。 @Jon:如果我输入的文本不在内容中,那么它必须返回 false。问题是“特定”和“文本”这两个词之间的空格。如果我搜索特定或文本,它会返回 true。这是在安卓上。
  • @Zooter:不,空格不是问题,因为空格也在文本中。您给出的确切代码检测“特定文本”。 String.contains 没有任何“单词”的概念——它只是在另一个字符序列中查找一个字符序列。

标签: java android regex pattern-matching string-matching


【解决方案1】:

如前所述,文本是多行的。找不到第一次出现 \n 之后的任何内容。我用空格替换了\n,它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2015-03-31
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多