Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How to limit regex optional characters to one of two values?

Asked by Christopher Paterson May 15, 2023 1.3K views 1 answer
Share

About this question

I am working up a regex that will match if the first character is 'S', 'U', or absent. I've gotten it to match the two characters just fine, but I can't figure out how to match the absent character. Here's what I have so far.

String a = 'S02-1234'; String b = 'T02-1234'; String c = 'U02-1234'; String d = '02-1234'; Pattern regex = Pattern.compile('([U|S])02-1234'); Matcher ma = regex.matcher(a); system.debug('S02-1234 ' + ma.matches()); Matcher mb = regex.matcher(b); system.debug('T02-1234 ' + mb.matches()); Matcher mc = regex.matcher(c); system.debug('U02-1234 ' + mc.matches()); Matcher md = regex.matcher(d); system.debug('02-1234 ' + md.matches());
String a match, GOOD!
String b does not match, GOOD!
String c matches, GOOD!
String d does not match, NOT good! :(

I've googled the question quite a bit, and suspect that I might not be using the right keyword. I'll bet it's something simple too... I just can't find it.

Your answer

1 Answer

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.