0

I am trying to build a regex pattern using the Pattern and Matcher classes in salesforce to find a exact match of a word . For eg. the word hot should be found in the 1st 3 string but not in the 4th one.

hot in here

It's hot

how hot is it

[email protected] --- > should not match.

I tried with the below code but cannot get it to work. Any help is appreciated.

String strRegEx = '\\bhot\\b';
String str = ' how hot is it';

Pattern MyPattern = Pattern.compile(strRegEx);
Matcher MyMatcher = MyPattern.matcher(str);
Boolean result = MyMatcher.matches();

3 Answers 3

1

Found the issue. It was not with the Regex pattern but with the Apex code.

 String strRegEx = '\\bhot\\b';
 String str = ' how hot is it';

 Pattern MyPattern = Pattern.compile(strRegEx);
 Matcher MyMatcher = MyPattern.matcher(str);
 Boolean result = MyMatcher.find();
0

Try this regex

String strResEx = '\\b(hot)\\b';

We need double \ as \b is special character.

Hope this helps.

2
  • Tried it by escaping the \b but it still returns false.
    – HSG
    Nov 13, 2014 at 13:13
  • Tried with the '\\b(hot)\\b' by adding word grouping but it still fails to match.
    – HSG
    Nov 13, 2014 at 13:37
-1
Pattern kiwiSaverPattern = Pattern.compile('[K]{1}[0-9]{6,7}');
Pattern nzrtSaverPattern = Pattern.compile('\\b[0-9]{5,6}\\b');
Matcher kiwiSaverMatcher;
Matcher nzrtMatcher;

String strSubject = 'This is a test K5535934 test subject K55345545 K12345 395020 20504 with NZRT Number in it 857389';
kiwiSaverMatcher = kiwiSaverPattern.matcher(strSubject);
nzrtMatcher = nzrtSaverPattern.matcher(strSubject);
Integer cnt = 0;
while(nzrtMatcher.find()){

    System.debug('========== Occurrence ' + nzrtMatcher.group(0));
    cnt++;   
}
System.debug('========= cnt ' + cnt);

Integer cntr = 0;
while(kiwiSaverMatcher.find()){

    System.debug('========== Occurrence ' + kiwiSaverMatcher.group(0));
    cntr++;   
}
System.debug('========= cntr ' + cntr);
1
  • Welcome to SFSE! Please take the tour and read How to Answer. Right now, this answer is what we call a code dump (a block of code with little or no explanation). Code dumps tend to be poor answers because they don't help people understand what the problem was, or how the code addresses the issue (so when faced with a similar, but different, problem, they'll be less likely to overcome it on their own). Code dumps also tend to generate a lot of back-and-forth in the comments like "that didn't work" and "try this instead", which makes it hard for others to follow.
    – Derek F
    Nov 24, 2019 at 22:49

You must log in to answer this question.

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