jn025
jn025

Reputation: 2895

Regex match part of word

I want to match part of a word and this works if the length of the word in the pattern is less than the string the I am matching, example:

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

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

outputs true. However if the length of the word is larger then it returns false, example:

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

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

So how can I match only part of the word?

Upvotes: 0

Views: 3557

Answers (2)

Stanislav
Stanislav

Reputation: 28136

You can use this pattern (?i).*(student).*, like

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

Where:

(?i) makes it caseinsensitive

.* means 0 or more any characters

and (student) is the concrete group of characters you want to find

For your purposes, you can delete (?i) to make it case sensitive or .* in the beginning or at the end of the pattern, to determine the position of required word in the string.

Upvotes: 3

dguay
dguay

Reputation: 1683

What about this?

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

Will match Student followed by anything else.

Upvotes: 0

Related Questions