简体   繁体   中英

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 - Passes - Correct

  • aaa.aaa-aaa - Passes - Correct

  • aaa-aaa - Fails - Incorrect

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]+)*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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