Regular expression for detecting round or square b

2020-06-23 08:52发布

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!

标签: regex
3条回答
够拽才男人
2楼-- · 2020-06-23 09:09

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

查看更多
祖国的老花朵
3楼-- · 2020-06-23 09:13

Easy to understand, more dialect agnostic and correct:

^([A-Z][A-Z][A-Z])\|\[[A-Z][A-Z][A-Z]\]$

You might have to change the escaping of parens and pipes depending on your regex dialect.

查看更多
来,给爷笑一个
4楼-- · 2020-06-23 09:25

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.

查看更多
登录 后发表回答