0

I tried hard to find a solution, but failed. A (very long) string ends like this:

... destination: US, NL, UK, FRA, GER

The goal is:

  • find all UPPERCASE-words (not only the mentioned above)
  • with one, two or three letters
  • only consider words after destination:

I finished the loop and successfully read all two-letter words of the whole string into a list:

@"\b[A-Z][A-Z]\b" 

But more precison is needed.

Any regex-expert can help?

2
  • would destination: US, NL (both at the same time) be valid, or does yor example mean, that it either has to be destination: US or destination: UK?
    – dognose
    Feb 6, 2013 at 7:30
  • @dognose I believe it is destination: US, NL, ... Feb 6, 2013 at 7:40

2 Answers 2

0

@"destination.*?([A-Z]+)\b" this is your regexp
+ means one or more times
.* means any character 0 or more times. and ? sign after that means lazy regexp. It will match characters until it finds the first uppercase. Without that sign in string "destination: ABCD" .* will match ": ABC"
after matching word you need will be in group 1. I don't know which language are you using

1
  • 1
    why are u using .*? when :\s* would be the more accurate solution according to tcs question? Also he states, that it needs to be 1 to 3 letter codes - so don't use + but {1,3} instead. @"destination:\s*([A-Z]{1,3})"
    – dognose
    Feb 6, 2013 at 7:27
0

What language are you using?

Here is an example in C#:

string regex = @"destination:\s*([A-Z]{1,3})(?:(?:,\s*)([A-Z]{1,3}))*";
var m = Regex.Match("... destination: US, NL, UK, FRA, GER", regex);

if (m.Success) {
    Console.WriteLine(m.Groups[1].Value);
    if (m.Groups[2].Success) {
        foreach (var capture in m.Groups[2].Captures) {
            Console.WriteLine(capture.ToString());
        }
    }
}

It prints:

US
NL
UK
FRA
GER

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.