1

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 matches, 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.

1 Answer 1

3

You're just missing the ?, which makes it optional (technically defined as 0 or 1 occurrences):

Pattern regex = Pattern.compile('([U|S])?02-1234'); 

Note that technically, using [], you don't want the | "operator", because you're actually checking if the string starts with U, S, or |. Similarly, you don't need the (), because it's not necessary here.

Pattern regex = Pattern.compile('[US]?02-1234'); 

[] is a "character class", which means "allow any one of the values in the bracket". You might want to read more about how regular expressions work; most people like to link to Regular Expressions to learn more about how to build proper regular expressions, and you can search on your favorite search engines for JavaScript-based sites that let you put in a pattern and a string to test.

4
  • My go-to
    – gNerb
    Commented Jul 18, 2018 at 15:25
  • @gNerb Yeah, there's lots of resources out there, people just need to go spend the time to go looking/searching. regexr that you linked to does look pretty nice, and I wasn't explicitly aware of it before, although I generally only need the docs when I run into esoteric use cases at this point.
    – sfdcfox
    Commented Jul 18, 2018 at 15:29
  • Im not so good at regex as I'm sure you've found out today :P regexr lets me copy the regex other people use and then it explains it to me which I really like.
    – gNerb
    Commented Jul 18, 2018 at 20:09
  • @gNerb I noticed that. It's really a nifty tool.
    – sfdcfox
    Commented Jul 18, 2018 at 20:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .