regex - What regular expression can verify the format of this type of string? -
I have to verify that a string is in a certain format ... here are the rules.
- May contain a colon and / or dot.
- Both colon and dot are optional
- If any colon and / or point is specified then there should be at least one letter
- if both are specified
- Li>
- Only 0 or 1 colon and 0 or 1 dot is allowed
-
Any string means more than one Unicode characters except colon and dot (colon And dot characters are not allowed as part of
AnyString ).
Example:
Maybe ...
AnyString: AnyString.AnyString AnyString: AnyString AnyString.AnyString AnyString
can not be ...
AnyString: .oststring AnyString.AnyString: AnyString AnyString: AnyString: any string Any string
I have tried too many combinations and I am not enough just to get it on regular expressions.
Thanks in advance
OK, it looks like this: < Ul>
- This definitely starts with one or more non-
- This optionally contains one or more colon after the non-colon or dot characters
- This is a dot after alternatively one or more non-colon-or-dot characters
- If "colon plus x" And the "dot plus x" section is both, so the colon The section should first come in
(Note that when you were written above, now you did not have any explanation edited, so it was based only on examples.) < / P>
So I was expecting to be a regex like this:
^ [^ ^] + (? :: [^.] +)? (?: \. ^ ^.: +)? $
Note:
-
You want to keep all of these literally in the string word to avoid h To avoid backslash, e.g.
var regex = new Regex ("^ ^ ^? (? :: [^.] +)? (?: \. [? ^ ^. +] $") ;
^ matches the beginning of a string
[^
- >>
+ is the syntax for "at least one"
(?: & Lt; subexpression & gt;) one
. The syntax for is
. means "any character"
? is a syntax for "zero or one" (ie optional)
$ matches the end of a string
Test code:
using the system; Using System.Text.RegularExpressions; Class Test {Static Readonly Reggae Reggae = New Reggae (@ "^ [^.] + (? :: [^.] +)? (?: \. ^ ^.] +)? $"); Static zero main () {asset ("AnyString: AnyString.AnyString", "AnyString: AnyString", "AnyString.AnyString", "AnyString"); AssertInvalid ("AnyString: .AnyString", "AnyString.AnyString: AnyString", "AnyString:", "AnyString: .. Anystring", "AnyString.", "AnyString", "AnyString"); } Fixed zero AssertValid (parameter string [] input) {foreach (different input in input) {ifge! (Regex.IsMatch (input)) {Console.WriteLine ("but not expected for match: {0}", input) ; }}} Static zero escape incorrect (parameter string [] input) {foreach (different input in input) {if (regex.IsMatch (input)) {Console.WriteLine ("not expected match, but done: {0}" , Input ); }}}}
Comments
Post a Comment