正则表达式允许单个连字符和下划线但不允许在字符串的开头或结尾 [英] Regex to allow single hyphen and underscore but not at beginning or end of string

查看:240
本文介绍了正则表达式允许单个连字符和下划线但不允许在字符串的开头或结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我修改了这个正则表达式以允许下划线、连字符、字母和数字.我正在尝试进一步修改它,使其具有以下属性:

I have this Regex I modified to allow underscores, hyphen, letters and numbers. I am trying to modify it further so that it has the following properties:

  1. 只允许数字、字母
  2. 允许在第一个和最后一个字符之间的任何位置使用下划线或连字符
  3. 不能下划线连字符开头(只能在第一个和最后一个字符).

这是我现在所拥有的:

^[a-zA-Z0-9_-]*$

推荐答案

试试这个:

^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$

或者这个,这将简单地确保字符串不以连字符或下划线开头:

Or this, which will simply ensure that the string does not start with a hyphen or underscore:

^[a-zA-Z0-9][a-zA-Z0-9_-]*$

这篇关于正则表达式允许单个连字符和下划线但不允许在字符串的开头或结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆