开发者

Regex for a string up to 20 chars long with a comma

I need to define a regex for a string with the following requirements:

  • Maximum 20 characters
  • Must be in the form Name,Surname
  • No numbers and开发者_如何学Go special characters allowed (again, it's a name&surname)

I already tried something like ^[^1-9\?\*\.\?\$\^\_]{1,20}[,][^1-9\?\*\.\?\$\^\_\-]{1,20}$ but as you can find, it also matches a 40 chars long string.

How can I check for the whole string's maximum length and at the same time impose 1 comma inside of it and obviously not at the borders?

Thank you


Try the regex:

^(?=[^,]+,[^,]+$)[a-zA-Z,]{1,20}$

Rubular Link

Explanation:

^                : Start anchor
(?=[^,]+,[^,]+$) : Positive lookahead to ensure string has exactly one comma
                   surrounded by at least one non-comma character on both sides.
[a-zA-Z,]{1,20}  : Ensure entire string is of length max 20 and has only
                   letters and comma
$                : End anchor


You can do this using forward negative assertions:

^(?!.{21})[A-Za-z]+,[A-Za-z]+$

The regex contains two parts now, the actual definition, and a statement at the start, saying that from that point, there will not be 21 characters.

So for the definition as stated above, the regex becomes

^(?!.{21})[^1-9\?*\.\?\$\^_\,]+,[^1-9\?*\.\?\$\^_\,]+$


The obvious answer would be: Don't ask for name and surname in the same input field.

If you still want to do it: There's no easy way that I know of, but here is a possibility. To see the principle think your [^1-9\?\*\.\?\$\^\_\,] instead of X (I added he \, since it's kind of important :-)).

^(X{1},X{19})|(X{2},X{18})|...|(X{19},X{1})$

Quite ugly, but should work.

On a different note: You don't capture nearly all special characters with your exclusive range. But it's probably still better than an inclusive range.


As I say, I think stated the way you have it, it's not matchable by a regular expression -- it's a pushdown language.

However, you could always split on ',' and match each substring, then total.


I have you tried your example, but removing the

{1,20} 

in the middle, leaving to try this:

^[[^1-9\?\*\.\?\$\^\_],[^1-9\?\*\.\?\$\^\_\-]]{1,20}$


Use:

[[a-zA-Z],[a-zA-Z]]{1,20}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜