|
Subject:
|
New help with Pattern in Java
|
|
Posted By:
|
2BOrNot2B
|
Post Date:
|
7/1/2008 12:14:18 PM
|
Hi.
I am working with Pattern and Matcher in Java. I need help creating a pattern to match the following strings:
MAIL FROM: MAIL FM: MAIL FROM:
This is what I have on my pattern, "MAIL\\s+FR{0,1}O{0,1}M:"
My pattern seem to work if the string is "MAIL FRM:" or "MAIL FOM:", which is incorrect.
Please help.
|
|
Reply By:
|
Old Pedant
|
Reply Date:
|
7/1/2008 4:40:56 PM
|
Well, sure. The pattern
"MAIL\\s+FR{0,1}O{0,1}M:"says:
MAIL == literally
\\s+ == one or more spaces
F == literally
R{0,1} == an optional letter R
O{0,1} == an optional letter O
M: == literally
There are a couple of ways to solve this:
"MAIL\\s+F(RO)?M:" That makes the *group* RO optional. And that certainly works.
But my own preference would be K.I.S.S.
"MAIL\\s+(FM|FROM)M:" That says "FM" or "FROM" as choices.
p.s.: No reason to ever use {0,1} when ? means the same thing.
|