douyu53265 2014-10-14 19:17
浏览 545
已采纳

正则表达式,以字母数字和连字符开头,在字符串中下划线

I'm trying to write a regexp in golang that matches strings that start as alphanumeric and can have an underscore or hyphen after, but not starting with a hyphen or underscore.

Here is what I could come up with, but this matches alphanumeric and hyphen underscore anywhere

[A-Za-z0-9_-]

So something like sea-food would match or seafood or sea_food, but not -seafood nor _seafood.

  • 写回答

3条回答 默认 最新

  • dongshan8953 2014-10-14 19:20
    关注

    You need to use a ^ to indicate the start of the string and $ for the end, and then use two character classes:

    ^[A-Za-z0-9][A-Za-z0-9_-]*$

    To disallow hyphens and underscores at the end of the string as well try:

    ^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架