[SalesForce] Apex regex pattern to match Space hyphen Integer

I have the following values for a custom picklist field

  1. Lower – L1
  2. Upper – L2
  3. Side – L3

What is the regex pattern to match the above values?

Mainly this pattern

   {anylength of string}{one space}{one hyphen}{one space}{L charecter}{one digit integer}

I have tried something this way but not working

String message = 'Upper - L2';
String regex = '[a-zA-Z\\sL\\s\\d{1}]*';
Pattern regexPattern = Pattern.compile(regex);
Matcher regexMatcher = regexPattern.matcher(message);
if(regexMatcher.matches() == true) {
   System.debug('Matched');
}

Best Answer

You have tried to make the regex using a character class, but that's simply incorrect.

You should find something like the following is more appropriate:

^.+ - L[0-9]$

This is:

  • Matching the whole value (start at the beginning with "^" and end at the end with "$")
  • Allowing any sequence of at least one character with ".+"
  • explicitly matching space, hyphen, space (this doesn't match tabs etc.)
  • explicitly matching "L" (this doesn't match "l")
  • allowing a single numeric digit between 0 and 9
Related Topic