多次匹配同一个未知字符 [英] match the same unknown character multiple times

查看:41
本文介绍了多次匹配同一个未知字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个似乎无法解决的正则表达式问题.我实际上不知道正则表达式是否可以做到这一点,但我需要在模式末尾匹配一系列字符 n 次.例如.blahblah[A-Z]{n}问题是与结束范围匹配的任何字符都必须相同.

I have a regex problem I can't seem to solve. I actually don't know if regex can do this, but I need to match a range of characters n times at the end of a pattern. eg. blahblah[A-Z]{n} The problem is whatever character matches the ending range need to be all the same.

比如我要匹配

  • blahblahAAAA
  • blahblahEEEEE
  • blahblahQQQQ

但不是

  • blahblahADFES
  • blahblahZYYYY

是否有一些正则表达式模式可以做到这一点?

Is there some regex pattern that can do this?

推荐答案

你可以使用这个模式:blahblah([A-Z])\1+

\1 是对第一个捕获组的反向引用,在本例中为 ([A-Z]).而 + 将匹配该字符一次或多次.要限制它,您可以使用 {n}+ 替换为特定的重复次数,例如 \1{3} 将匹配三遍.

The \1 is a back-reference to the first capture group, in this case ([A-Z]). And the + will match that character one or more times. To limit it you can replace the + with a specific number of repetitions using {n}, such as \1{3} which will match it three times.

如果您需要匹配整个字符串,请确保分别以 ^ 为前缀并以 $ 结尾,以便模式变为 ^blahblah([AZ])\1+$

If you need the entire string to match then be sure to prefix with ^ and end with $, respectively, so that the pattern becomes ^blahblah([A-Z])\1+$

您可以在此处阅读有关反向引用的更多信息.

You can read more about back-references here.

这篇关于多次匹配同一个未知字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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