I need to verify that a string is in a certain format…here are the rules.
- Can contain a colon and/or dot.
- Both the colon and dot are optional
- If a colon and/or dot is specified there must be at least one character to the left and one character to the right of the colon/dot.
- The colon must be before the dot if both are specified
- Only 0 or 1 colon and 0 or 1 dot is allowed
AnyStringmeans a string of one or more unicode characters excluding colon and dot (colon and dot characters are not allowed as part ofAnyString).
Examples:
Can be…
AnyString:AnyString.AnyString
AnyString:AnyString
AnyString.AnyString
AnyString
Cannot be…
AnyString:.AnyString
AnyString.AnyString:AnyString
AnyString:
AnyString.
:AnyString
.AnyString
I have tried lots of different combinations and I am just not good enough at Regular Expressions to get this one.
Thanks in advance
Well, that looks like:
(Note that none of your now-edited-in explanation was present when I wrote the above, so it was just based on the examples.)
So I’d expect that to be a regex like this:
Notes:
You’d want to put all of this in a verbatim string literal to avoid having to escape the backslashes, e.g.
^matches the start of a string[^.:]will match any character other than dot or colon+is the syntax for “at least one”(?:<subexpression>)is the syntax for a non-capturing group\.is an escaped dot, as.means “any character”?is the syntax for “zero or one” (i.e. optional)$matches the end of a stringTest code: