正则表达式匹配A,AB,ABC,但不匹配AC。 (“以”开头“) [英] Regular expression to match A, AB, ABC, but not AC. ("starts with")

查看:2768
本文介绍了正则表达式匹配A,AB,ABC,但不匹配AC。 (“以”开头“)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正撞在墙上。我想要一个匹配的正则表达式:空字符串, A AB ABC ,但不是 AC 。我有这个,有效:

I'm banging my head against a wall. I want a regex that matches: empty string, A, AB, and ABC, but not AC. I have this, which works:

/^(A|AB|ABC)?$/

但这是一种简化;在我的应用程序 A B C 实际上是长字符类,所以我不想一遍又一遍地重复它们。也许我只是没有以正确的方式看待它。我试过这个:

But this is a simplification; in my app A, B, and C are actually long character classes, so I don't want to repeat them over and over. Maybe I'm just not looking at it the right way. I tried this:

/^((AB?)C?)?$/

但仍然匹配 AC

有没有更简单的方法,可以扩展到(比方说), ABCD ABCDE 等等?

Is there a simpler way to do this, that could be extended to (say), ABCD, ABCDE, etc.?

编辑:扩展到 ABCDE ,我的意思是匹配:空字符串, A AB ABC ABCD ABCDE 。基本上,以开头正则表达式。

Edit: By extend to ABCDE, I mean it would match: empty string, A, AB, ABC, ABCD, ABCDE. Basically, a "starts with" regex.

推荐答案

试试这个正则表达式:

^(A(B(C)?)?)?$

我认为您可以看到该模式并将其扩展为 ABCD ABCDE ,如:

I think you can see the pattern and expand it for ABCD and ABCDE like:

^(A(B(C(D)?)?)?)?$
^(A(B(C(D(E)?)?)?)?)?$

现在每个部分都依赖于前面部分( B 取决于 A C 取决于 B 等)。

Now each part depends on the preceeding parts (B depends on A, C depends on B, etc.).

这篇关于正则表达式匹配A,AB,ABC,但不匹配AC。 (“以”开头“)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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