duanhu2414 2017-08-15 00:02
浏览 196
已采纳

正则表达式解析跟随五个特定前缀之一的行中的所有单词

Consider

$email = "Name: John Smith 

          Phone: 1-888-555-5555
          ...";

Suppose I have the code above, and I need to filter the line after the word "Name: ". I have been doing:

if (preg_match("/Name:*? (.*)/m", $email, $g) === 1){
    echo $g[1]."
"; //John Smith
}

What is a way to write the regex statement if the string didn't explicitly start with the word "Name: ", but one of 5 variations of it? Here are the five different formats I am working with:

  • Name:
  • Full Name:
  • F. Name:
  • First/Last Name:
  • Name.
  • 写回答

2条回答 默认 最新

  • douchongbc72264 2017-08-15 00:46
    关注

    This can be done with several different possible patterns.

    This is the php code to demonstrate your pattern implementation

    $email='Name: John Smith
            Phone: 1-888-555-5555
            ...';
    
    if(preg_match('/Name[:.] \K[^
    ]*/',$email,$g)){
        echo $g[0]; //John Smith
    }
    
    echo "
    
    ---
    
    ";
    
    $mult='Name: John Smith
            Phone: 1-888-555-5555
            ...
            Name. Jane Smith
            Phone: 1-888-555-5556
            ...
            First/Last Name: Joe Smith
            Phone: 1-888-555-5557
            ...
    ';
    
    var_export(preg_match_all('/Name[:.] \K[^
    ]*/',$mult,$g)?$g[0]:'fail');
    

    Pattern #1: (more lenient) /Name[:.] \K[^ ]*/ Demo

    Pattern #2: (more literal) ~(?:Name.|(?:F(?:. |ull |irst/Last ))?Name:) \K[^ ]*~ Demo

    Some notes:

    • [:.] means match either of the characters (colon or dot).
    • \K means "start the fullstring match from this point in the pattern".
    • [^ ]* means match zero or more characters that are not line return or new line characters.
    • the delimiter in Pattern #2 is changed from / to ~ so that the slash between irst and Last doesn't have to be escaped.
    • the m flag is not necessary.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘