douzhongjian0752 2014-12-08 23:16
浏览 59
已采纳

正则表达式从IPv4八位字节修剪前导零

I am using the following regex in a PHP script to collect IPv4 Addresses and to also perform some validation of the IPv4 addresses.

A txt file of IPs is read into an array with a file() command, then a foreach loop using preg_match and this regex matches the IPv4 addresses.

However, it currently includes any leading zeros before each octet.

Is it possible to improve this regex to trim any leading zeros in each octet without completely discarding IPs with leading zeros? I would prefer to do this in a single regex instead of adding an additional function to clear the leading zeros.

/(?:(?: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]?)/

Correct output:

38.10.125.242
38.1.1.24

Incorrect output:

038.010.125.242
038.001.001.024

I have been using Lumadis.be to test, but none of the regexes that I tried from other answers in Stack Overflow seem to work?.

  • 写回答

2条回答 默认 最新

  • doujiang1993 2014-12-09 00:42
    关注

    Simpler is just:

    preg_replace('/\b0+/', '', $str);
    

    Since we know the only word boundaries are at the . and the start/end of line

    Edit: it looks like we need a lookahead to avoid empty octets

    preg_replace('/\b0+(?=\d)/', '', $str)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证