区分大小写和不区分大小写 [英] Case sensitive and insensitive in the same pattern

查看:306
本文介绍了区分大小写和不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢我以前的作业问题的帮助 Regex以匹配诸如< A>,< BB>,< CCC>但不是< ABC> ,但现在我还有另一个作业问题。

Thanks to the help with my previous homework question Regex to match tags like <A>, <BB>, <CCC> but not <ABC>, but now I have another homework question.

我需要匹配< LOL> < LOLOLOL> (3个大写字母,后两个字母可重复),但不包含< lol> (需要大写)。

I need to match tags like <LOL>, <LOLOLOL> (3 uppercase letters, with repeatable last two letters), but not <lol> (need to be uppercase).

使用以前作业中的技巧,我尝试了< [AZ]([AZ] [AZ])\1 *> 。这样做是有效的,除了有一个额外的限制:重复部分可以是大小写混合的!

Using the technique from the previous homework, I tried <[A-Z]([A-Z][A-Z])\1*>. This works, except there's an additional catch: the repeating part can be in mixed case!

所以我还需要匹配< LOLolol> < LOLOLOlol> ,因为它是3个大写字母,在混合大小写的情况下可重复使用最后两个字母。我知道您可以使用 / i 使模式不区分大小写,这将使我匹配< LOLolol> 使用我拥有的正则表达式,但现在它也将匹配< lololol> ,因为前三个字母的检查也不区分大小写。

So I need to also match <LOLolol>, <LOLOLOlol>, because it's 3 uppercase letters, with repeatable last two letters in mixed case. I know you can make a pattern case-insensitive with /i, and that will let me match <LOLolol> with the regex I have, but it will also now match <lololol>, because the check for the first 3 letters are also case-insensitive.

那么我该怎么做?如何区分前三个字母区分大小写,然后区分其余字母区分大小写?

So how do I do this? How can I check the first 3 letters case sensitively, and then the rest of the letters case-insensitively? Is this possible with regex?

推荐答案

是的!实际上,您可以使用嵌入式修饰符以某些方式执行此操作。这会将修饰符放入模式中,您基本上可以选择修饰符应用于模式的哪个部分。

Yes! You can in fact do this in some flavors, using what is called embedded modifier. This puts the modifier in the pattern, and you can essentially select which parts of the pattern the modifiers apply to.

不区分大小写的嵌入式修饰符是(?i),因此在这种情况下需要的模式是:

The embedded modifier for case insensitivity is (?i), so the pattern you want in this case is:

<[A-Z]([A-Z]{2})(?i:\1*)>



参考文献




  • regular-expressions.info/Modifiers


    • 在正则表达式中指定模式


      • 代替 / regex / i ,您还可以执行 /(?i)regex /

      • References

        • regular-expressions.info/Modifiers
          • Specifying Modes Inside The Regular Expression
            • Instead of /regex/i, you can also do /(?i)regex/

              • 您还可以执行 / first(?i)second(?-i )third /

              • You can also do /first(?i)second(?-i)third/

              • 您还可以执行 / first(?i:second)third /

              • You can also do /first(?i:second)third/

              这篇关于区分大小写和不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆