❱❯❈❯❁❂❯❂❅✱❲❯❁❁✱❳❯❁❇✱❴❯❁❄✱❔❯❂❁✱❸❯❀✱❹❯❁❃✱❽❯❁❉✱❾❯❉✱✾❯❁❀❯❁❆✱✿❯❅❯❆❯❂❀✱❿❯❁❈✱➀❯❃❯❇✱❂❯❂❄✱➃❯❂❂✱➄❯❁❯❂✱➅❯❁❅✱❉❯❂❃✱❊❯❄✱

最近由于工作需要详细的了解了一下正则表达式.

关于字符串的处理,本质上就是找规律,找到开头结尾,再从中间获取到自己想要的值.

善于使用 ()圈出想要的分组 使用?:取消掉自己不想要的值

例如:我想从以下字符串中获取出IP和每次的延时和TTL

Pinging baidu.com [180.149.132.47] with 32 bytes of data:
Reply from 180.149.132.47: bytes=32 time=24ms TTL=46
Reply from 180.149.132.47: bytes=32 time=25ms TTL=46
Reply from 180.149.132.47: bytes=32 time=24ms TTL=46
Reply from 180.149.132.47: bytes=32 time=25ms TTL=46

Ping statistics for 180.149.132.47:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 24ms, Maximum = 25ms, Average = 24ms

正则可以写成 from ((?:\d{1,3}\.){3}\d{1,3})[\s\S]*?time=(.*)ms TTL=(\d*)

(?:\d{1,3}\.){3} 匹配 数字一到三个加. 一起出现三次 (?:\d{1,3}\.){3}\d{1,3})匹配IPV4 加括号取到IPV4的值

这样 匹配出4组数组每组数据有3个分组

0 1 2 3
from 180.149.132.47: bytes=32 time=24ms TTL=46 180.149.132.47 24 46
from 180.149.132.47: bytes=32 time=25ms TTL=46 180.149.132.47 25 46
from 180.149.132.47: bytes=32 time=24ms TTL=46 180.149.132.47 24 46
from 180.149.132.47: bytes=32 time=25ms TTL=46 180.149.132.47 25 46

 

正则应该一点一点从头开始写,没写一点都要测试你写的正则是否正确.

点开是正则的文档

Continue reading