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
pixelpixel 

Nuances of RegEx and Pattern Group matches

I'm trying to verify a Time (not DateTime) value entered in a text string as being valid that will be appended to a Date value in a trigger.

 

The pattern I think I need is (([0][1-9])|([1][0-2]))([U+003A])([0-5][0-9])([\b])([AP])([M]). Apex doesn't seem to like the [\b] which is there as a means to verify that there's a blank space. It also doesn't seem to like a [\s] in it's place either. I'm not entirely certain that either of those is exactly what's needed to designate that I'm looking for a blank space. Could anyone tell me what the most appropriate designator is to use is? I'd also like to verify that [U+003A] is what I need to use to search for a unicode colon.

 

With the RegEx portion out of the way, what's the best way to set up a pattern match of this kind? I've seen it done where each group is matched separately and others where they're entered as the entire RegEx pattern.

 

I've been trying get code similar to the following to work which keeps giving me a fatal error, even when I try debugging it by entering a static value for opp.Event_Start_Time__c:

 

 Pattern TimePttrn = Pattern.compile('(([1][0-2])|([0][1-9]))[U+003A]([0-5][0-9])[\b]([AP])([M])'); // hh:mm aaa'
 if (opp.Event_Start_Time__c != null){
    Matcher m = TimePttrn.matcher(opp.Event_Start_Time__c);
    boolean hasMatch = m.matches();
    system.assert(hasMatch == true);
    strtTm = m.group(0); 
    }
 
Is there something I've missed or am approaching from the wrong direction? Any helpful input greatly appreciated.
 
 
Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

Because \ is an escape character in Apex Code (e.g. \\ for backspace, \' for a literal single quote, etc), patterns have to have their \ characters escaped using another \. So instead of \b, it's \\b, and for \s it would be \\s.

All Answers

sfdcfoxsfdcfox

Because \ is an escape character in Apex Code (e.g. \\ for backspace, \' for a literal single quote, etc), patterns have to have their \ characters escaped using another \. So instead of \b, it's \\b, and for \s it would be \\s.

This was selected as the best answer
pixelpixel

Thank you sir, that's very helpful. I suspected the problems I was having with RegEx might be something along those lines! Am working in the Developer Console right now and see if that solves all of my problems! If it does, I'll mark this as "solved".

pixelpixel

Unfortunately, it seems the Developer Console wants to choke on any kind of backslash characters I enter, regardless of whether it's one or two! :(

pixelpixel

Ooops!, that did work! I had a mismatched pair of parens causing it not to work! TY for the assistance on the backslash. The other issues seem to be starting to sort themselves out now too! :)