0

我的要求是检查一组单词或单个单词是否存在于较大的字符串中。我尝试使用 String.contains() 方法,但如果较大的字符串具有换行符,则会失败。目前我正在使用regex下面提到的。但这仅适用于一个词。搜索到的文本是用户输入的值,可以包含多个单词。这是一个安卓应用程序。

String regex = ".*.{0}" + searchText + ".{0}.*";
Pattern pattern = Pattern.compile(regex);
pattern.matcher(largerString).find();

Sample String
String largerString    ="John writes about this, and John writes about that," +
" and John writes about everything. ";

String searchText = "about this";
4

2 回答 2

0

这是不使用正则表达式的代码。

String largerString    = "John writes about this, and John writes about that," +" and John writes about everything. ";
String searchText = "about this";
Pattern pattern = Pattern.compile(searchText);
Matcher m = pattern.matcher(largerString);

if(m.find()){
System.out.println(m.group().toString());
}

结果:

about this

我希望它会帮助你。

于 2014-06-19T09:08:22.593 回答
0

为什么不直接用空格替换换行符,然后将其全部转换为小写呢?

    String s = "hello";
    String originalString = "Does this contain \n Hello?";
    String formattedString = originalString.toLowerCase().replace("\n", " ");
    System.out.println(formattedString.contains(s));

编辑:考虑一下,我真的不明白换行符如何产生影响......

编辑2:我是对的。换行无关紧要。

        String s = "hello";
        String originalString = "Does this contain \nHello?";
        String formattedString = originalString.toLowerCase();
        System.out.println(formattedString.contains(s));
于 2014-06-19T08:55:15.790 回答