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条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改