The issue is not Pattern.quote
, but rather your use of Matcher.find:
Attempts to find the next subsequence of the input sequence that matches the pattern. This method returns true if a subsequence of the input sequence matches this Matcher object's pattern.
So Matcher.find
skips non-matching data to find the next match.
Whole word matching requires you to use the word boundary matchers like \b
, while whole input matching is achieved using Matcher.matches:
Attempts to match the entire region against the pattern.
To find whole words, within the over-all input, containing certain character sequences you simply need to tweak your code thus:
String datum= 'Looking into dataframe or DataFrame';
Pattern p = Pattern.Compile('(?i)\\b\\w*' + Pattern.quote('af') + '\\w*\\b');
Matcher m = p.matcher(datum);
while (m.find()) {
Integer s = m.groupCount();
for (Integer i = 0; i <= s; i++) {
System.debug(m.group(i));
}
}
This looks for a case-insensitive match against:
- A word boundary
- Followed by zero or more word class characters
- Followed by your quoted search term
- Followed by zero or more word class characters
- Followed by a word boundary