Case sensitive and insensitive in the same pattern

北战南征 提交于 2019-12-18 05:54:15

问题


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.

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

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!

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?


回答1:


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.

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

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

References

  • regular-expressions.info/Modifiers
    • Specifying Modes Inside The Regular Expression
      • Instead of /regex/i, you can also do /(?i)regex/
    • Turning Modes On and Off for Only Part of The Regular Expression
      • You can also do /first(?i)second(?-i)third/
    • Modifier Spans
      • You can also do /first(?i:second)third/


来源:https://stackoverflow.com/questions/3117159/case-sensitive-and-insensitive-in-the-same-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!