在正则表达式中指定 glob 大小范围

发布于 2024-08-09 01:06:36 字数 135 浏览 7 评论 0原文

如何定义某个模式应重复自身的最小和最大(可能无界)次数?我知道有 ?*,我可以通过重复一定次数来构建模式,但我知道使用 有一个特殊的表示法{},我只是不记得它是怎么回事。

How do I define a minimum and maximum (possibly unbounded) number of times a certain pattern should repeat itself? I know there's ? and *, with which I could build the pattern by repeating it a certain amount of times, but I know there's a special notation for it using {}, I just can't remember how it is.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

红衣飘飘貌似仙 2024-08-16 01:06:36

对于最小值 m 和最大值 n,您可以使用 {m,n}。如果mn相同,则只需使用{m}

例如,仅包含三到四个字母,后跟两个数字,后跟六到十二个字母数字的行将是:

^[A-Za-z]{3,4}[0-9]{2}[A-Za-z0-9]{6,12}$

如果您希望在高端无限重复(没有最大数量),只需省略 n.对于低端的无限重复,有些实现不支持省略 m 因此您可能只想指定 0 以确保安全)。换句话说,

[a-z]{6,}[0-9]{0,4}

意味着六个或更多小写字母后跟零到四位数字。

您的特殊情况只是其中的版本,如下所示:

'[a-z]?' is identical to '[a-z]{0,1}'
'[a-z]*'                 '[a-z]{0,}'
'[a-z]+'                 '[a-z]{1,}'

For a minimum of m and maximum of n, you use {m,n}. If m and n are the same, just use {m}.

For example, a line consisting only of three to four alphas followed by two numerics followed by six to twelve alphanumerics would be:

^[A-Za-z]{3,4}[0-9]{2}[A-Za-z0-9]{6,12}$

Where you want unbounded repetitions on the high side (no maximum number), just leave out the n. For unbounded repetitions on the low side, there are some implementations that don't support leaving out the m so you may want to just specify 0 for that to be safe). In other words,

[a-z]{6,}[0-9]{0,4}

means six or more lowercase letters followed by zero to four digits.

Your special cases are just versions of that, as in:

'[a-z]?' is identical to '[a-z]{0,1}'
'[a-z]*'                 '[a-z]{0,}'
'[a-z]+'                 '[a-z]{1,}'
尤怨 2024-08-16 01:06:36

模式后包括 {min,max}

After the pattern include {min,max}

数理化全能战士 2024-08-16 01:06:36

You can find a tutorial about repetition in Regex (as well as a bunch of other stuff) here

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