drtsd7864 2015-03-26 22:42
浏览 33
已采纳

PHP正则表达式改变依赖于字符串

I have a String like so

2*O#QR   4 F0 P0 A0 J4 C2 D0 I0 Y9 LHRDOH 1505 2345      388 0E

And to get the data I require I have the following regex

^(\d)+[^#$]*[#$](?'code1'\p{Lu}{2})\s*(?'code2'\d{1,4})\b\s*(?<seat1>[A-Z][0-9.](?:\s+[A-Z][0-9.])*+)\s+(?<from>[A-Z]{3})(?<to>[A-Z]{3})\s+(?<other>.*\S)\s*

The problem is that the regex I am using obtains the airline code, seats, from, to and other information. So for the above string it would look something like

1. `2`
code1 `QR`
code2 `4`
seat1 `F0 P0 A0 J4 C2 D0 I0 Y9`
from `LHR`
to `DOH`
other `1505 2345 388 0E`

Sometimes however I get a string like the following which the regex will fail on

3*O#QR 904 J4 C2 D0 I0 Y9 B9 H9 K9    MEL 0055 2125 #1   77W 0E

The difference in the above string is there is no from, only a to (MEL). Is there any way of changing my regex to only look for from and to if they are both present? If not, just look for to?

Thanks

  • 写回答

1条回答 默认 最新

  • duanqianhuan3994 2015-03-26 22:55
    关注

    The problem is this part of your regex

    (?<to>[A-Z]{3})\s+(?<other>.*\S)
    

    It requires you have something that matches (?<to>[A-Z]{3}) prior to a space. If you change this part of it to be

    (?<to>[A-Z]{3})?\s+(?<other>.*\S)
    

    That is, adding a ? after (?<to>[A-Z]{3}) and before \s

    It will tell the regex to expect zero or more of that pattern.

    Making your final working pattern

    ^(\d)+[^#$]*[#$](?'code1'\p{Lu}{2})\s*(?'code2'\d{1,4})\b\s*(?<seat1>[A-Z][0-9.](?:\s+[A-Z][0-9.])*+)\s+(?<from>[A-Z]{3})(?<to>[A-Z]{3})?\s+(?<other>.*\S)\s*
    

    I hope that made sense

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图