查找字符串中字符的多个非连续出现 [英] Find multiple, non consecutive, occurrences of a character in string

查看:73
本文介绍了查找字符串中字符的多个非连续出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我写RegEx表达式吗,它可以检查一个字符串是否包含一个以上的大写字母(或小写字母,无关紧要)字母,但不能连续出现.我需要在一个字符串中至少出现两次(甚至更好的n次).如果n = 2,则有效情况为密码,密码或密码.

Can somebody please help me write RegEx expression which can check if a string contains more than one occurrence of a uppercase (or lowercase, doesn't matter) letter but not in a row. I need to have at least two (or even better n) occurrences in a string. If n=2 valid situations would be PassWord or PAssword or PASSWord.

当我尝试使用此/(?=([A-Z] {2,3}))/g 时,它匹配PassWOrd,但不匹配PassWord.

When I tried this /(?=([A-Z]{2,3}))/g it matched PassWOrd but not PassWord.

对我来说奇怪的是,它也与PaSSWOrd相匹配.我以为{2,3}中的3实际上意味着最多将匹配3个大写字符.SSWO为什么匹配?

What is strange to me is that it also matched PaSSWOrd. I thought 3 in {2,3} actually means that no more that 3 Uppercase characters will be matched. Why is SSWO matched?

我尝试了类似的变体,但没有一个对我有用(因为我对RegEx不太熟悉,这并不奇怪).

I tried similar variations but non of them worked for me (nothing strange as i'm not very familiar with RegEx).

可以使用RegEx做到吗?

Can this be done using RegEx?

推荐答案

(?=([AZ] {2,3}))正则表达式匹配2到3个连续大写ASCII字母字符串中的任意位置.您想匹配一个仅包含2到3个大写ASCII字母的字符串,而不必连续.

The (?=([A-Z]{2,3})) regex matches 2 to 3 consecutive uppercase ASCII letters anywhere inside a string. You want to match a string that only contains 2 to 3 uppercase ASCII letters, not necessarily consecutively.

要匹配仅包含两个大写ASCII字母(不多不少)的字符串,请使用以下表达式:

To match a string that only contains two uppercase ASCII letters (no more no less), use the following expression:

^(?:[^A-Z]*[A-Z]){2}[^A-Z]*$

或者,如果您只允许在整个字符串中使用ASCII字母:

Or, if you only allow ASCII letters in the whole string:

^(?:[a-z]*[A-Z]){2}[a-z]*$

请参见 模式详细信息

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