如何正则表达式匹配一串数字和连字符,但不以连字符开头或结尾?
我有一些代码验证 1 到 32 个字符的字符串,该字符串可能只包含字母数字和连字符 ('-'),但可能不以连字符开头或结尾。
我正在使用 PCRE 正则表达式 & PHP(尽管 PHP 部分在本例中并不重要)。
现在,伪代码如下所示:
if (match("/^[\p{L}0-9][\p{L}0-9-]{0,31}$/u", string)
and
not match("/-$/", string))
print "success!"
也就是说,我首先检查字符串的内容是否正确,是否带有“-”并且长度是否正确,然后我正在运行另一个测试看看它不以“-”结尾。
关于将其合并到单个 PCRE 正则表达式中,有什么建议吗?
我尝试过使用前瞻/后视断言,但无法使其工作。
I have some code validating a string of 1 to 32 characters, which may contain only alpha-numerics and hyphens ('-') but may not begin or end with a hyphen.
I'm using PCRE regular expressions & PHP (albeit the PHP part is not really important in this case).
Right now the pseudo-code looks like this:
if (match("/^[\p{L}0-9][\p{L}0-9-]{0,31}$/u", string)
and
not match("/-$/", string))
print "success!"
That is, I'm checking first that the string is of right contents, doesn't being with a '-' and is of the right length, and then I'm running another test to see that it doesn't end with a '-'.
Any suggestions on merging this into a single PCRE regular expression?
I've tried using look-ahead / look-behind assertions but couldn't get it to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这个正则表达式:
如果你想使用环视断言:
Try this regular expression:
And if you want to use look-around assertions:
另一种稍微另类的方法是将您的角色类保持在一个整体中,并具体说明您不想允许使用连字符的点。
另请注意每个人似乎总是忘记的
D
修饰符。最后,为了确定,您知道
\pL
会比a-zA-Z
匹配更多,对吗?只是检查。A slightly alternative approach would be to keep your character class in one piece and be specific about the points where you don't want to allow the hyphen.
Also note the
D
modifier which everyone always seems to forget.Finally, just to be sure, you are aware that
\pL
will match much more thana-zA-Z
, right? Just checking.