如何正则表达式匹配一串数字和连字符,但不以连字符开头或结尾?

发布于 2024-08-30 05:15:31 字数 423 浏览 5 评论 0原文

我有一些代码验证 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南汐寒笙箫 2024-09-06 05:15:31

尝试这个正则表达式:

/^[\p{L}0-9](?:[\p{L}0-9-]{0,30}[\p{L}0-9])?$/u

如果你想使用环视断言:

/^[\p{L}0-9][\p{L}0-9-]{0,31}$(?<!-)/u

Try this regular expression:

/^[\p{L}0-9](?:[\p{L}0-9-]{0,30}[\p{L}0-9])?$/u

And if you want to use look-around assertions:

/^[\p{L}0-9][\p{L}0-9-]{0,31}$(?<!-)/u
笑咖 2024-09-06 05:15:31

另一种稍微另类的方法是将您的角色类保持在一个整体中,并具体说明您不想允许使用连字符的点。

/^(?!-)[\p{L}0-9-]{1,32}(?<!-)$/Du

另请注意每个人似乎总是忘记的 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.

/^(?!-)[\p{L}0-9-]{1,32}(?<!-)$/Du

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 than a-zA-Z, right? Just checking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文