0

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

3
  • 1
    Please try to rephrase your question to explain exactly what you mean. Often, you can actually solve it yourself if you try to do that. In this case, think in the lines of 'What am I actually (exactly) trying to match with this regular expression?' Commented Mar 26, 2015 at 22:43
  • I have rephrased it so hopefully it is clearer. I have a feeling I need a question mark in the regex but not 100% sure Commented Mar 26, 2015 at 22:52
  • oh, think I solved it by adding a ? after the from brackets, thanks Commented Mar 26, 2015 at 22:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Literally figured it out seconds before you posted this. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.