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 regular expression spaces 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'); }
Answered by ankur Dwivedi

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

You should find something like the following is more appropriate:

^.+ - L[0-9]$

This is:

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



Your Answer

Interviews

Parent Categories