如何使用正则表达式来处理这种条件情况?
- 以字母数字
^[a-z0-9]
开头 - ,然后是可选的点
\.?
- 如果有一个点,则后面必须跟 2 到 4 个字母
[az]{2,4}
- 必须以字母结尾
[az]$
- 必须是一个点,且最多只能是两个点。
它就像域名:
yahoo.co.uk
或 yahoo.com
,但您不能执行此 yahoo.co.u
或此 >yahoo.co.
,是的,类似的东西。
- Begins with alphanumeric
^[a-z0-9]
- Then followed by this optional dot
\.?
- If there is a dot, then it MUST be followed by 2 to 4 alphabets
[a-z]{2,4}
- It must be ends with an alphabet
[a-z]$
- It has to be a dot and only two dots max.
it's like domain names:
yahoo.co.uk
or yahoo.com
, but you cannot do this yahoo.co.u
or this yahoo.co.
, yes something like that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将可选点与其后面必须包含的 2-4 个字符组合在一起:
(\.[az]{2,4})
。也就是说,您要么没有,要么最多有两组点 + 字母字符(\.[az]{2,4}){0,2}
。必须以
[az]
部分结尾,您可以使用正向查找(?<=[az])
进行检查,将其作为完整的正则表达式:这将在Perl 和 PHP 正则表达式 (PCRE),但在 JavaScript 中则不然,因为它不支持lookbehind。在这种特定情况下,您可以解决该限制。
如果至少有一个点,则已经保证它将以
[az]
结尾,因为该测试位于该点所属的组中。如果没有点,则需要在末尾强制添加一个[az]
。为此,您可以将一个或多个量词 (+
) 转换为零个或多个量词 (*
),并强制结尾为[az]
当没有“点组”时。当存在点组时,您可以保持相同的图案,但现在至少有一个强制点。You can group the optional dot with the 2-4 characters that must follow it:
(\.[a-z]{2,4})
. That said, you will have either none, or up to two of these groups of dot + alphabetic characters(\.[a-z]{2,4}){0,2}
.The must end with
[a-z]
part, you can check with a positive lookbehind(?<=[a-z])
giving this as the full regex:This will work in Perl and PHP regexes (PCRE), but not in JavaScript, because it does not support lookbehind. In this specific case, you can work around that limitation.
If there is at least one dot, there's already a guarantee that it will end in
[a-z]
, because that test is in the group that the dot is a part of. If there is no dot, you need to force a[a-z]
at the end. To do this you can turn the one-or-more quantifier (+
) into a zero-or-more (*
) and force the end to be an[a-z]
when there are no "dot groups". When there are dot groups, you can keep the same pattern, but now with at least one mandatory dot.这会检查以
[az][0-9]
开头,然后包含一两个点,后跟 2/4 字母的字符串。它适用于您提供的示例(至少在 Python 中)(对于yahoo.co.uk
和yahoo.com
为 true,对于yahoo.co 为 false。 u
和yahoo.co.
)编辑 - 重新阅读后,我想您可能需要这个:
这将匹配不包含点但包含点的字符串(除上述之外)以字母结尾,例如
yahoo
,但不是yahoo2
。This checks for a string that begins with
[a-z][0-9]
and then contains one or two dots followed by 2/4 alphabets. It works (in Python, at least) for the examples you provided (true foryahoo.co.uk
andyahoo.com
, false foryahoo.co.u
andyahoo.co.
)Edit - upon re-reading, I think you may want this instead:
This will match strings (in addition to the above) that do not include dots but end with a letter, such as
yahoo
, but notyahoo2
.试试这个:
Try this: