0

How can we do a keyword search with special characters in a string with pattern and matcher class I used similar code as below to do the same. However this does not work if there are special characters like ( , ), - present in the keyword. I tried using \w to the code but it did not work.

static Boolean keywordSearch(String input, String keywordPhrase)
{
    return Pattern.compile('(?i)\\b\\w' + keywordPhrase + '\\b\\w').matcher(input).find();

}

String corpus = 'The quick brown fox jumps over the lazy (dog)';
system.assert(keywordSearch(corpus, 'lazy (dog)')); //Fails and it is not detected
system.assert(keywordSearch(corpus, 'QUICK')); // Pass
system.assert(!keywordSearch(corpus, 'jump')); //Pass
0

1 Answer 1

2

The problem here is that if your keyword ends with a non-word character, wrapping it in word boundary tokens will fail to match. If you want to still find exact matches, you may wish to conditionally add the \b tokens based on if the keword phrase starts or ends with word boundaries. You probably also want to escape non-word, non-space characters.

Pattern startsWordBoundary = Pattern.compile('^\\b'); // ^ matches start of string
Pattern endsWordBoundary = Pattern.compile('\\b$');   // $ matches end of string

static Boolean keywordSearch(String input, String keywordPhrase)
{
    String expression = '(?i)';

    if (startsWordBoundary.matcher(keywordPhrase).find()) expression += '\\b';
    expression += escapeExpression(keywordPhrase);
    if (endsWordBoundary.matcher(keywordPhrase).find()) expression += '\\b';

    return Pattern.compile(expression).matcher(input).find();
}
static String escapeExpression(String phrase)
{
    return phrase.replaceAll('([^\\w\\s])', '\\\\$0');
}

String corpus = 'The quick brown fox jumps over the lazy (dog)';
system.assert(keywordSearch(corpus, 'lazy (dog)'));
system.assert(keywordSearch(corpus, 'QUICK'));
system.assert(!keywordSearch(corpus, 'jump'));
3
  • Thanks a lot Adrian. Let me try this out. It will be great if you could direct me to any link where i can dive deep to understand the \\b, \\w, ?i tags. I could not find it as far as i googled. Thanks again for helping.. Commented Sep 8, 2016 at 5:43
  • Hi @adrian.. this worked. Thanks for helping! It will be great if you coul d point me to any link where i can find details about these tags Commented Sep 8, 2016 at 10:09
  • I juse regex101.com
    – Adrian Larson
    Commented Sep 8, 2016 at 11:01

You must log in to answer this question.

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