0

I was trying to implement a case insensitive whole word searching pattern. I came up with the following pattern:

Pattern p = Pattern.Compile('(?i)'+Pattern.quote('af'));

Using it in the code below:

String datum= 'Looking into  dataframe or DataFrame';

Pattern p = Pattern.Compile('(?i)'+Pattern.quote('af'));
Matcher m = p.matcher(datum);
while (m.find()) {
    Integer s = m.groupCount();
    for (Integer i = 0; i <= s; i++) {
        System.debug(m.group(i));
    }
}

It matches af, aF which are just part of word and is not an exact match.

Am I missing something?

1 Answer 1

1

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:

  1. A word boundary
  2. Followed by zero or more word class characters
  3. Followed by your quoted search term
  4. Followed by zero or more word class characters
  5. Followed by a word boundary
7
  • What should I be using Instead?@philW Commented Sep 26, 2022 at 9:46
  • Entirely depends on exactly what you are trying to do. If you want to match the entire input, just use Matcher.matches.
    – Phil W
    Commented Sep 26, 2022 at 9:49
  • I want to extract the words which are being matched. Commented Sep 26, 2022 at 9:52
  • Can you modify the code to match exact searches only, Like if the string only contains sf and not dataframe, since dataframe is being returned here. Thanks in advance Commented Sep 26, 2022 at 10:21
  • 1
    I encourage you to read the documentation and the related Java documentation for details as to what you can and cannot do with regex in Salesforce. It's not clear from your question exactly what you are trying to do. Do you want the search term to be a whole word? If so, simply remove the zero or more word class character parts from my example (i.e. the \\w* before and after your quoted search term).
    – Phil W
    Commented Sep 26, 2022 at 10:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .