简体   繁体   English

正则表达式匹配只有2个大写字母的字符串

[英]Regex to match a string with 2 capital letters only

I want to write a regex which will match a string only if the string consists of two capital letters. 我想编写一个正则表达式,只有当字符串由两个大写字母组成时才匹配字符串。

I tried - [AZ]{2}, [AZ]{2, 2} and [AZ][AZ] but these only match the string 'CAS' while I am looking to match only if the string is two capital letters like 'CA'. 我试过了 - [AZ]{2}, [AZ]{2, 2} and [AZ][AZ]但这些只匹配字符串'CAS',而我希望匹配时只有字符串是两个大写字母,如' CA”。

You could use anchors: 你可以使用锚点:

^[A-Z]{2}$

^ matches the beginning of the string, while $ matches its end. ^匹配字符串的开头,而$匹配其结尾。


Note in your attempts, you used [AZ]{2, 2} which should actually be [AZ]{2,2} (without space) to mean the same thing as the others. 请注意,在您的尝试中,您使用[AZ]{2, 2} [AZ]{2,2}实际上应该是[AZ]{2,2} (没有空格)与其他人的意思相同。

You need to add word boundaries, 你需要添加单词边界,

\b[A-Z]{2}\b

DEMO DEMO

Explanation: 说明:

  • \\b Matches between a word character and a non-word character. \\b单词字符和非单词字符之间的匹配。
  • [AZ]{2} Matches exactly two capital letters. [AZ]{2}正好匹配两个大写字母。
  • \\b Matches between a word character and a non-word character. \\b单词字符和非单词字符之间的匹配。

You could try: 你可以尝试:

\b[A-Z]{2}\b 

\\b matches a word boundary. \\ b匹配单词边界。

Try = 试试=

^[A-Z][A-Z]$ 

Just added start and end points for the string. 只需添加字符串的起点和终点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM