dongyao9762 2017-09-28 20:23
浏览 28
已采纳

正则表达式在=后获得值

I'm trying to get the values ad.test.com and 768 from the string "adress=ad.test.com port=768" with this regex but it doesn't work :/

$res = preg_split("/^adresse=([a-z]).*port=([0-9]{3})/", $test) ; 
  • 写回答

2条回答 默认 最新

  • douwen1213 2017-09-28 20:29
    关注

    This should capture the 2 data points you want:

    ^adress=([a-z.]+).*port=([0-9]{3})
    

    You also want to use this with preg_match, not preg_split.

    preg_match('/^adress=([a-z.]+).*port=([0-9]{3})/s', 'adress=ad.test.com
     port=768', $match);
    echo $match[1] . ' ' . $match[2];
    

    Demo: https://3v4l.org/Ih929

    Notes on why your regex failed:

    1. Character class missing ., and the character class wasn't quantified.
    2. adress is in your string but you are looking for addresse in your regex
    3. . doesn't match new lines unless the s modifier is used.

    Regex demo: https://regex101.com/r/3MSiDh/1/

    A more accurate regex that won't require s modifier:

    ^adress=([a-z.]+?)\s*port=(\d{3})
    

    Demo 2: https://regex101.com/r/3MSiDh/3/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)