dsxjot8620 2014-09-23 20:22
浏览 62
已采纳

Regex的替代方法,用于从字符串中提取信息

I'm attempt to extract information from a string, which will always be in the same format.

The format will always be:

To:
                     Name here
Date:
                     26/08/2014 14:52
Order Number:
                     123456
Service Required:
                     Plumbing
Service Response:
                     48 Hour
Service Limit:
                     110.00

123 TEST ROAD
LEEDS
LS1 1HL

Contact:
                     Mr J Smith - 0777 123456
Telephone:
                     01921 123456

Work Details:

Notes here etc 

I have tried exploding the string by spaces and looping through the array but I cannot structure it in such a way that I receive the information.

E.g: I try to retrieve "Name here" from after "To:" without also retrieving "Date: etc..", the eventual idea is to create variables for each bit of information so i can enter it into a database.

Any help/suggestions/idea's are really welcome.

thanks for reading

  • 写回答

4条回答 默认 最新

  • doudouwd2017 2014-09-23 20:45
    关注

    You could use regex easily.

    If you use this regex, you can get the name here:

    To:\s+(.*)
    

    Working demo

    enter image description here

    The idea of this regex is to look for the key you want to look for and fetch the value. For instance, above regex looks for To: whitespaces and store in a capturing group the content.

    You just need to change To for whatever you want, if you modify it to Date you will get the date.

    enter image description here

    As a note, this only works with single line values.

    The code to implement this regex in php is very straightforward, like this:

    $re = "/To:\\s+(.*)/";
    $str = "YOUR STRING HERE";
    preg_match($re, $str, $matches);
    

    On the other hand, below data follows a different pattern:

    123 TEST ROAD
    LEEDS
    LS1 1HL
    

    You'd need a different regex pattern too, so to fetch that information you could use:

    ^(\w+[\w\s]+)(?!:)$
    

    Working demo

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

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?