简体   繁体   English

正则表达式接受-字符

[英]Regular Expression to accept - character

I currently have a regular expression to validate a field within my application which looks like this: 我目前有一个正则表达式来验证我的应用程序中的字段,如下所示:

^(?:(?:\\w|[-])+\\.(?:(?:(?:\\w|[-])+|\\.))*(?:\\/(?:\\w|[-])*)*|\\w*)$

Unfortunately some aspects of this does not work. 不幸的是,这在某些方面是行不通的。

  • aaa - Passes - Correct aaa-通过- 正确

  • aaa.aaa - Passes - Correct aaa.aaa-通过- 正确

  • aaa.aaa-aaa - Passes - Correct aaa.aaa-aaa-通过- 正确

  • aaa-aaa - Fails - Incorrect aaa-aaa-失败- 不正确

How am I able to change my regular expression in order to make the last scenario pass? 我如何更改正则表达式以使最后一个场景通过?

The first \\. 第一\\. causes your last expression to fail. 导致您的最后一个表达式失败。 Since there are more groups, the first part of your expression has to match. 由于存在更多的组,因此表达式的第一部分必须匹配。

If you make the dot optional, your expression works. 如果将点设为可选,则表达式有效。

Not sure, but maybe you can simplify the expression like this: 不确定,但是也许您可以像这样简化表达式:

[A-Za-z]+([\-\.][A-Za-z]+)*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM