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
trustchristrustchris 

problem with the Matcher method, lookingAt()

Hi All

 

I am trying to create a script that checks domains to make sure they are of the correct format.  I have succesfully compiled my regex and and can use this with the Matcher method to check that the input string is of the correct format.  for example.

 

boolean  myMatcher = Pattern.matches('\\w*-*\\w*[^-].com.au', 'google.com.au');
system.assert(myMatcher);

//this code will execute succesfully in the system log.

 

This is fine when I want to confirm a whole string, but when trying to match a patial string I thought I'd be able to use the lookingAt method to dtirmine the regionStart & regionEnd points and extract the part of the domain that is useful.

 

Using the lookingAt method, I would expext the following code to execute succesfully.

 

pattern myPattern = pattern.compile('\\w*-*\\w*[^-].com.au');
system.debug('the pattern is - '+ myPattern.pattern());
boolean myMatcher = myPattern.matcher('www.google.com.au').lookingAt();
system.assert(myMatcher);

//does not find the google.com.au domain in www.google.com.au.

 

It seems as though the lookingAt method is the same as the Matcher method and is attempting to match the whole string.

 

Maybe it's just my understanding of how this works that is wrong?  Anybody got any ideas?

 

Cheers

 

Best Answer chosen by Admin (Salesforce Developers) 
trustchristrustchris

Just incase anyone else comes up againsr this, I have found the solution

 

the lookingAt method only matches from the start of the string.  so if you have values before the matching content in your string, this method returns false.  I assumed from the documentation that it would start looking at the beginning of the region, and work through 'til it found a match... not the case!

 

Instead, use the find() method. this will return the start and end points of the first match in the input string.  for example, this code executes correctly.

 

string sampledomain = 'http://www.google.com.au';
pattern myPattern = pattern.compile('\\w*-*\\w*[^-].com.au');
system.debug('the pattern is - '+ myPattern.pattern());
//instantiate a matcher object using the compliled pattern.
matcher myMatcher = myPattern.matcher(sampledomain);
myMatcher.find();
integer startint = myMatcher.start();
integer endint = myMatcher.end()-1;
system.debug('start and stop values - '+startint+'-'+endint);

//debug log returns 11 & 23, the start and stop values of my region!