4

我对正则表达式相当陌生,我使用它们的次数越多,我就越喜欢它们。我正在研究一个必须满足以下条件的正则表达式:

  1. 必须以 Alpha 字符开头
  2. 在接下来的三个字符中,至少一个必须是 Alpha 字符。
  3. 前四个字符之后的任何内容都是自动匹配。

我目前有以下正则表达式:^[a-zA-Z](?=.*[a-zA-Z]).{1}.*$

我遇到的问题是,我的积极前瞻(?=.*[a-zA-Z]).{1}并不局限于字母字符之后的下三个字符。

我觉得好像我在这里错过了一个概念。我从这个表达中遗漏了什么?

谢谢大家。

4

4 回答 4

3

The .* in your lookahead is doing that. You should limit the range here like

^[a-zA-Z](?=.{0,2}[a-zA-Z]).{1}.*$

Edit: If you want to make sure, that there are a least 4 characters in the string, you could use another lookahead like this:

 ^[a-zA-Z](?=.{3})(?=.{0,2}[a-zA-Z]).{1}.*$
于 2010-06-04T13:25:37.380 回答
3

What do you want lookahead for? Why not just use

^[a-zA-Z](..[a-zA-Z]|.[a-zA-Z].|[a-zA-Z]..)

and be happy?

于 2010-06-04T13:26:41.013 回答
1

你可能不得不做一个解决方法。就像是:

^[a-z](?=([a-z]..|.[a-z].|..[a-z])).{3}.*
  • 第一个字符 [az]
  • 正前瞻,第一个、第二个或第三个字符是 az([a-z]..|.[a-z].|..[a-z])
  • 其他的东西
于 2010-06-04T13:17:35.767 回答
0

改变*你的前瞻?以获得m/^[a-zA-Z](?=.?[a-zA-Z]).{1}.*$

如果我理解你的标准,那会因为贪婪的变化而修复它。

这些是正确匹配的:

a2a3-match
2aaa-no match
Aaaa-match
a333-no match
于 2010-06-04T13:34:36.640 回答