One joyful day (Thu, 09 Sep 2004 07:49:03 GMT to be precise), Alan Moore
I want to validate a string that should respect the rules:
a. Should not contain two or more consecutive dots
b. Any ASCII graphic (printing) character may appear except:
@ \ ", [ ]
The above excluded characters are also allowed if they are quoted either by
using a backslash ("\") before each excluded character or by surrounding the
entire local-part that contains one or more excluded character(s) with
double-quote characters.
So if there are three double-quotes in a row, should it be interpreted
a single, escaped double-quote? No, that would make the job
prohibitively complex (if not impossible), so I'll assume that a
double-quote can only be escaped with a backslash.
Although this seems like a case of doing somebody's homework for them,
I'll jump in here since your assertion seems incorrect.
Three double-quotes in a row is easily accommodated by:
\".+\"
Placing this at the start of the regexp group will allow it to contain
any number of " characters since the final one will be used (and
necessary) to complete the pattern match. Regular expressions are, by
default, greedy but exhaustive. That is, they will eat as much as they
can whilst allowing the patten to match.
The first predicate is achieved via lookahead as you said by:
\\.(?!\\.)
The backslash escape can't use lookbehind for the \ since this would
require allowing it in a non-escape context (it must first be allowed
before it can be used as a lookbehind), so a normal match is required:
\\\\[@\"\\\\\\[\\]]
Giving a regexp of:
"^(?:" +
"\".+\"" + "|" +
"\\\\[@\"\\\\\\[\\]]" + "|" +
"\\.(?!\\.)" + "|" +
"[^@\"\\\\\\[\\]\\.]" +
")*$")
And a test demo:
String test_data[] = new String[]
{
"This is a pass test",
"This is a .. fail test",
"This @ is also a fail test",
"This is a \\@ \\\" pass test",
"This is also a \"@[]\"\"@[\"]\" \\@ \\[ \\] pass test",
"This is a \"\"\" \\\" pass test",
"This is a \"#ABC[]blah\" pass test",
"This is a [fail] test"
};
Pattern pattern = Pattern.compile(
"^(?:" +
"\".+\"" + "|" +
"\\\\[@\"\\\\\\[\\]]" + "|" +
"\\.(?!\\.)" + "|" +
"[^@\"\\\\\\[\\]\\.]" +
")*$");
System.out.println("Trying data...");
for (int i = 0; i < test_data.length; ++i)
{
String test_string = test_data
;
System.out.print(" Testing: '" + test_string + "': ");
System.out.println(pattern.matcher(test_string).matches() ?
"Pass" : "Fail");
}
System.out.println("...done");
Mark Wright
- (e-mail address removed)
================Today's Thought====================
"In places where books are burned, one day,
people will be burned" - Heinrich Heine, Germany -
100 years later, Hitler proved him right
===================================================