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!
How do you use square brackets in regex? Use square brackets ( [] ) to create a matching list that will match on any one of the characters in the list. Virtually all regular expression metacharacters lose their special meaning and are treated as regular characters when used within square brackets.
How do you use round brackets in regex? By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Square brackets ( “[ ]” ): Any expression within square brackets [ ] is a character set; if any one of the characters matches the search string, the regex will pass the test return true.
Your regular expression seems like it is try to match too much, try this one:
^[(\[][A-Z]{3}[)\]]$
^
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
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:
.([A-Z]{3}).((?<=\(...\))|(?<=\[...\]))
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 .
:
(.[A-Z]{3}.)((?<=\(...\))|(?<=\[...\]))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With