I'm trying to find aiport codes given a string like (JFK)
or [FRA]
using a regular expression.
I'm don't have to make sure if the mentioned airport code is correct. The braces can pretty much contain any three capital letters.
Here's my current solution which does work for round brackets but not for square brackets:
[((\[]([A-Z]{{3}})[))\]]
Thanks!
Your regular expression seems like it is try to match too much, try this one:
^
matches the beginning of the line (something you may or may not need)[(\[]
is a character class that matches(
or[
[A-Z]{3}
matches three capitol letters[)\]]
is a character class that matches)
or]
$
matches the end of the line (something you may or may not need)Click here to see the test results
Note that
[
and]
are special characters in regular expressions and I had to escape them with a\
to indicate I wanted a literal character.Hope this helps
Easy to understand, more dialect agnostic and correct:
You might have to change the escaping of parens and pipes depending on your regex dialect.
if you want to (1) match the letters in a single matching group and (2) only match parens or brackets (not one of each) then it's quite hard. one solution is:
where the first part matches the letters and the trailing mess checks the brackets/parens.
see http://fiddle.re/u19v - this matches
[ABC]
and(DEF)
, but not(PQR]
(which the "correct" answer does).if you want the parens in the match, move the capturing parens outside the
.
:the underlying problem here is that regexes are not powerful enough to match pairs of values (like parens or brackets) in the way you would like. so each different kind of pair has to be handled separately.