duandi1636 2015-11-27 09:30
浏览 74
已采纳

正则表达式匹配user @ domain:port

I have to match a string as user@domain:port. So it should allow domain or domain:port or user@domain or user@domain:port complete. Initially i had written multiple regular expressions to match some of these conditions as following:

preg_match('/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $str) or preg_match('/^[A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $str) or preg_match('/^[A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}+([:][0-9]+)$/', $str)

but now i have to cover all conditions as above and i think there should be a single expression which will pass all conditions.

Can someone please tell me the correct regular exp to match all conditions with some explanation?

I want to do it in PHP.

  • 写回答

2条回答 默认 最新

  • douyu0845 2015-11-27 09:42
    关注

    Here is something to help you

    The regex

    ^(?:([\w-]+)@)?([\w-\.]+\.[a-zA-Z][\w-]+)(?::([0-9]{1,5}))?$
    

    Should do what you want. Let's explain : You first want to match (if it exist) a user followed by @. To match a word you can use \w but in your regex you specified that you wanted the char - wich isn't include in \w (but _ is). So to match your user you will do :

    (?:([\w-]*)@)?
    

    Then you want to match a domain name

    ([\w-\.]+\.[a-zA-Z][\w-]+)
    

    The domain name have to finish by at least one dot followed by a word (the top level domain). The top level domain doesn't begin by a digit (this rule was created based on the usedTopLevelDomainList

    And to finish you want to match a port wich is a 1-5 digit :

    (?::([0-9]{0,5}))?
    

    As pointed out the regex can match IPv4 that aren't within the 255 max range. The regex to verify an IPv4 is :

    ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
    

    Source. I've updated the previous regex to exclude the IP match from my regex and add a OR statement for the domain name to match either an IPv4 based on the above regex or a domain as I've defined it previously.

    Result with group to separate each part :

    ^(?:([\w-]+)@)?((?:[\w-\.]+\.[a-zA-Z][\w-]+)|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::([0-9]{1,5}))?$
    

    Result without any group to just match valid case :

    ^(?:[\w-]+@)?(?:(?:[\w-\.]+\.[a-zA-Z][\w-]+)|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::[0-9]{1,5})?$
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用