I'm trying to validate a string in an xsd that requires the use of a regex. The string will take the form of the following...
JOE~PETE~SAM~BOB
and the following are considered valid...
JOE
~PETE
JOE开发者_如何学JAVA~SAM~
~~~BOB
JOE~PETE~~
also, each of the names between the ~ can only be a maximum of 6 characters (or digits) and there can only be a maximum of 4 names.
The regex I'm trying right now is...
[0-9a-zA-Z]{0,6}[~]{0,1}|[0-9a-zA-Z]{0,6}[~]{1}[0-9a-zA-Z]{0,4}[~]{0,1}
but am wondering if their is a better solution.
NOTE: I should clarify a bit further... if there are only 4 names allowed, that means there would only be 3 ~'s at the most allowed. The tildes denote position, so if ~~~BOB occurred, that would mean the position 1,2, and 3 were empty, and the 4th was occupied by BOB. Also, if the you had JOE~~~, JOE is in the first position, and the rest are empty. Zero or more names could be in any of the 4 positions. Also, symbols like .,*, space, and others are allowed.
i think this is what you're getting at
^[^~]{0,6}(~[^~]{0,6}){0,3}$
How about this?
^(~*\b[0-9a-zA-Z]{1,6}\b~*){0,4}$
Assuming there is no limit to the number of ~
s between, before, and after the names.
The \b
escape sequence matches "borders" between words - that is, the space between any alphanumeric and any non-alphanumeric character.
Also, Pro Tip: the \w
escape sequence matches the same thing as [0-9a-zA-Z]
. The above regex could be shortened to:
^(~*\b\w{1,6}\b~*){0,4}$
Are empty strings valid? What about strings consisting solely of tildes? If so, the following will work:
^([0-9a-zA-Z]{0,6}~?){0,4}$
精彩评论