我想检查字符串中是否存在单词或一组单词

时间:2014-06-19 08:50:01

标签: java android regex pattern-matching wordsearch

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

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";

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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

我希望它会对你有所帮助。