正则表达式匹配词的一部分

时间:2015-10-18 03:55:11

标签: java regex

我希望匹配单词的一部分,如果模式中单词的长度小于我匹配的字符串,则此方法有效,例如:

Pattern p = Pattern.compile("Stude");
Matcher m = p.matcher("Student");

System.out.println(m.find())

输出true。但是,如果单词的长度较大,则返回false,例如:

Pattern p = Pattern.compile("Studentsrter");
Matcher m = p.matcher("Student");

System.out.println(m.find())

那我怎么才能匹配单词的一部分?

2 个答案:

答案 0 :(得分:2)

您可以使用此模式(?i).*(student).*,例如

Pattern p = Pattern.compile("(?i).*(student).*");
Matcher m = p.matcher("asaStudentstrtr");

其中:

(?i)使其具有不敏感性

.*表示0或更多任何字符

(student)是您要查找的具体字符组

出于您的目的,您可以删除(?i)以使其区分大小写或在模式的开头或结尾处.*,以确定字符串中所需单词的位置。

答案 1 :(得分:0)

这个怎么样?

Pattern p = Pattern.compile("(Student).*");

将匹配学生,其他任何内容。