[英]How to write a RegEx to check for a certain, specific number of characters?
I am trying to test a string for a state code, the regex I have is 我正在尝试为状态代码测试字符串,我拥有的正则表达式是
^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$
The issue is, if I have something like "CTA12" as a test string, it will get a match of CT. 问题是,如果我将“ CTA12”之类的东西作为测试字符串,它将获得CT匹配项。 How can I modify my regex to make it only match state codes that are not part of a larger string? 如何修改我的正则表达式,使其仅匹配不属于较大字符串的状态代码?
Your use of anchors with alternation is incorrect, ^AB|DC$
means "strings that start with AB
or end with DC
". 您使用的锚交替使用是不正确的, ^AB|DC$
表示“以AB
开头或以DC
结尾的字符串”。 To get the ^
and $
to both apply to each element of the alternation, you need to put the alternation in a group, for example ^(AB|DC)$
. 为了使^
和$
都适用于交替的每个元素,您需要将交替放在一个组中,例如^(AB|DC)$
。
Try changing your regex to the following: 尝试将正则表达式更改为以下内容:
^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$
The alternative to using a group is to put the ^
and $
as a part of each element in the alternation, for example ^AB$|^DC$
, but that would make your regex significantly longer so a group is the way to go. 使用组的另一种方法是将^
和$
作为交替元素中每个元素的一部分,例如^AB$|^DC$
,但这会使您的正则表达式长得多,因此使用组是一种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.