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
Justin Cairns 14Justin Cairns 14 

Starts with Alpha or Starts with Numeric

Is there a way to write logic that can determine if a value starts with any alpha character or any numeric character?  Example would be we want to know if a string begins with an 2 alpha characters.  Or we want to know if it begins with any 3 numeric values.  Or a combination.  

@@#####  So this would indicate the string should start with any 2 alpha and then have 5 numeric.  This will be used in an APEX batch process uses a rules table to determine if records meet one of the defined criteria.  So we would need a way to define the mapping and then a way to check it in APEX.  Any help would be appreciated.  Thanks.  
Best Answer chosen by Justin Cairns 14
Lalit Mistry 21Lalit Mistry 21
Hi Justin,
Below pattern/matcher should help you.
Use below pattern to check for string starting with 2 alphabets followed by 5 numeric characters.
Pattern alphaNumPattern = Pattern.compile('[a-zA-Z]{2}[0-9]{5}');

System.debug(alphaNumPattern.matcher('ab12345').matches());  //results true
System.debug(alphaNumPattern.matcher('abc23456').matches()); //results false
System.debug(alphaNumPattern.matcher('a123456').matches()); //results false

 

All Answers

Lalit Mistry 21Lalit Mistry 21
Hi Justin,
Below pattern/matcher should help you.
Use below pattern to check for string starting with 2 alphabets followed by 5 numeric characters.
Pattern alphaNumPattern = Pattern.compile('[a-zA-Z]{2}[0-9]{5}');

System.debug(alphaNumPattern.matcher('ab12345').matches());  //results true
System.debug(alphaNumPattern.matcher('abc23456').matches()); //results false
System.debug(alphaNumPattern.matcher('a123456').matches()); //results false

 
This was selected as the best answer
Justin Cairns 14Justin Cairns 14
Lalit, this is perfect.  Thanks!