有没有更好的方法来编写这个 IF 语句?

发布于 2024-12-11 20:35:17 字数 1456 浏览 3 评论 0原文

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

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

发布评论

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

评论(5

老娘不死你永远是小三 2024-12-18 20:35:17

是的,有。如果你使用正则表达式,你也可以使用一个正则表达式,就像这样。通过使用字符串锚点的开始或字符串/结束符,也可以跳过长度。

if ($colour && preg_match("/^#([0-9a-fA-F]){3}(([0-9a-fA-F]){3})?$/", $colour)
{
}

我认为可以跳过“检查价值”,但这作为一种优化可能是有意义的。

[编辑]

事实证明这是 RegEx 备忘单上的示例< /a>.

Yes, there are. If you use RegEx, you can just as well use one regex, like this. The length can be skipped too, by using start or string/end of string anchors.

if ($colour && preg_match("/^#([0-9a-fA-F]){3}(([0-9a-fA-F]){3})?$/", $colour)
{
}

I think the 'check for value' can be skipped to, but that might make sense as an optimization.

[edit]

It turns out to be an example on the RegEx cheat sheet.

草莓味的萝莉 2024-12-18 20:35:17

让正则表达式通过添加表示字符串开始/结束的 ^ 和 $ 符号并组合正则表达式来检查字符串的长度:

if (preg_match("/^#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}$/", $colour)) {

Let your regular expressions check the length of the string by adding the ^ and $ signs signaling start/end of a string, and combining your regular expressions:

if (preg_match("/^#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}$/", $colour)) {
浅语花开 2024-12-18 20:35:17
if (preg_match("/^#([0-9a-f]{3}){1,2}$/i", $colour)) {

对我来说似乎足够了。

if (preg_match("/^#([0-9a-f]{3}){1,2}$/i", $colour)) {

seems enough to me.

她说她爱他 2024-12-18 20:35:17

您可以使用 ^$ 锚定正则表达式,以便隐含长度。

if( $colour && 
    (  preg_match("/^#[0-9a-fA-F]{6}$/",$colour)
    || preg_match("/^#[0-9a-fA-F]{3}$/",$colour)
  ) ) {

我不太了解 php,但在 perl 中,您需要将 $ 转义为 \$ 或使用单引号。

You could anchor your regex with ^ and $ so the length is implied.

if( $colour && 
    (  preg_match("/^#[0-9a-fA-F]{6}$/",$colour)
    || preg_match("/^#[0-9a-fA-F]{3}$/",$colour)
  ) ) {

I don't know php that well, but in perl you would need to escape the $ as \$ or use single quotes instead.

美煞众生 2024-12-18 20:35:17

您的正则表达式已经指定了字符串的长度,因此如果您设置开始 ^ 和结束 $ 边界,则无需检查它:

if ( preg_match("/^#[0-9a-fA-F]{6}$/", $colour) || preg_match("/^#[0-9a-fA-F]{3}$/",$colour) ) {}

Your regexp already specify stings' lenghts so you do not need to check it if you set start ^ and end $ boundaries:

if ( preg_match("/^#[0-9a-fA-F]{6}$/", $colour) || preg_match("/^#[0-9a-fA-F]{3}$/",$colour) ) {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文