简体   繁体   English

如何编写RegEx来检查特定数量的特定字符?

[英]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.

相关问题 如何编写javascript正则表达式来检查单个字符,除了3个特定字符外,其他任何字符都不能跟随 - How to write a javascript regex to check for a single character that can be followed by anything but 3 specific characters JavaScript正则表达式检查某些字符 - JavaScript Regex to check for certain characters Javascript RegEx可以检查字符串中一定数量的数字字符,而与其他字符无关 - Javascript RegEx to check a certain number of Numeric characters in string regardless of other characters 如何在正则表达式中的字符串后隔离一定数量的字符 - How isolate a certain number of characters after a string in regex javascript正则表达式检查网址中的某些特殊字符 - javascript regex to check for certain special characters in a url 正则表达式禁止使用特定顺序的某些字符 - Regex to disallow certain characters in specific sequence Javascript正则表达式 - 无序字符串中的特定字符数 - Javascript regex - specific number of characters in unordered string 正则表达式检查数字是否排除特定数字 - Regex check if number excludes specific digits 如何在JS中为前2个字符编写正则表达式可以是数字或字母,然后是连字符,然后是6位数字? - How to write regex in JS for first 2 characters can be digit or alphabet and followed by hyphen and then 6 digit number? 正则表达式在一定数量的字符和空格后添加\\ n - regex to add \n after certain number of characters and space
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM