0

I need to perform a keyword search in a string that exact match.

EmailTemplate et = [SELECT Id htmlValue FROM EmailTemplate where Name = 'Welcome Email'];

string htmlValue = et.htmlValue; 

string s1 = 'Hello there {!Contact.Name},';
string s2 = 'Did you know {!Contact.Deal} this is a test?';

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

system.assert(keywordSearch(htmlValue, s1));

I want to match exact like word to word except the case sensitive, I have tried using contains or equals but that does not work word to word, if I skip ? which is in string s2 and use contains it does pass the assert which is suppose to get failed

3
  • 1
    Can you give some examples or matches and non matches? Not sure what you mean by "word to word".
    – Eric
    Commented Sep 1, 2017 at 3:22
  • Pattern has special regex rules, so I'm not surprised this does not behave as expected.
    – sfdcfox
    Commented Sep 1, 2017 at 3:32
  • @Eric: "word to word" means EXACT match. I'm trying to match the exact string
    – Nick
    Commented Sep 1, 2017 at 13:17

1 Answer 1

2

Two issues that I see...

  1. Your search phrases include special characters in Regex, so you should use Pattern.quote() to account for that
  2. Not convinced that you should really be using \b to find a word boundary. You can probably just get rid of that part.

So, I would write it like this:

string htmlValue = 'blah hello there {!Contact.Name}, blah';

string s1 = 'Hello there {!Contact.Name},';
string s2 = 'Did you know {!Contact.Deal} this is a test?';

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

system.debug(keywordSearch(htmlValue, s1));
5
  • that was an example so if I have other special characters?
    – Nick
    Commented Sep 1, 2017 at 13:04
  • if you remove the , from s1 it still returns true technically it should returns false
    – Nick
    Commented Sep 1, 2017 at 13:13
  • It should work with any special characters. Since we're using Pattern.quote to handle special chars, that will sort out anything that could cause trouble for a regex. Deleting the comma from the end of s1 should still return true. The test string still contains the whole of s1. If you remove the comma from htmlValue, then it does return false - which is what you would expect
    – Aidan
    Commented Sep 1, 2017 at 13:20
  • what is ?i means
    – Nick
    Commented Sep 1, 2017 at 13:22
  • The ?i was taken from your original post. It means that the search is case insensitive, see docs.oracle.com/javase/6/docs/api/java/util/regex/… That page overall gives you a reference to what is available in Apex regular expressions.
    – Aidan
    Commented Sep 1, 2017 at 13:25

You must log in to answer this question.

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