function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC LearningSFDC Learning 

Regex Pattern is not working

Hi,
I am looking out for the regex match for the Exact string. 

For Example The sentence is: Hi there is cow and cowis white.and i want to remove only 'cow' string. 

String s2 = 'Hi there is cow and cowis white';
String strRegEx ='\\[cow]\\';

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

if(MyMatcher.find()) {
   s2 = s2.replaceall(strRegEx, ' ');
}

It is not working and if it woking the result is retunrs is 'Hi there is and is white'. Basically i just want to ignore the substrings to be removed.

Thanks in advance.
Raj VakatiRaj Vakati
Use this code
 
String s2 = 'Hi there is cow and cowis white';
String strRegEx ='(?:^|\W)cow(?:$|\W)';

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

if(MyMatcher.find()) {
   s2 = s2.replaceall(strRegEx, ' ');
}

 
SFDC LearningSFDC Learning
Hi Raj,

It is throwing error: Compile Error: Illegal string literal: Invalid string literal '(?:^|\W)cow(?:$|\W)'. Illegal character sequence \W' in string literal

Thanks
Raj VakatiRaj Vakati
Working Copy
 
String s2 = 'Hi there is cow and cowis white';
String strRegEx ='\\bcow\\b';

Pattern MyPattern = Pattern.compile(strRegEx);
Matcher MyMatcher = MyPattern.matcher(s2);
Boolean result = MyMatcher.find();
System.debug('result'+result);
if(result) {
   String s3 = s2.replaceall(strRegEx, ' ');
    System.debug('s3---->>'+s3);
}

 
Raj VakatiRaj Vakati
Its working ?