正则表达式-超前断言 [英] Regex - lookahead assertion
问题描述
我对前瞻性断言(?=)有问题.例如,我有表达:
I have problem with lookahead assertion (?=). For example, I have expression:
/Win(?=2000)/
如果表达式类似于Win2000
,Win2000fgF
,则匹配Win
.我有下一个表情:
It match Win
, if expression is like Win2000
, Win2000fgF
. I have next expression:
^(?=.*\d)(?=.*[a-z]).*$
它与数字和小写字母匹配,例如:45dF
,4Dd
.但是我不知道为什么它能工作并匹配所有字符:)我没有字符,在(?=.*\d)
之前.我认为,只有这种表达方式才能起作用:
It match for digit and lower case letter, for example: 45dF
, 4Dd
. But I don't know, why it works and match all characters :) I haven't characters, which are before (?=.*\d)
. I think, only this expression should work:
^.\*(?=.*\d)(?=.*[a-z]).*$
(表达式前带有\*
).
你能解释一下吗?
推荐答案
假设我们是正则表达式引擎,并将正则表达式^(?=.*\d)(?=.*[a-z]).*$
应用于字符串2a
.
Let's say we are the regex engine and apply the regex ^(?=.*\d)(?=.*[a-z]).*$
to the string 2a
.
从位置0开始(在第一个字符之前):
Starting at position 0 (before the first character):
-
^
:确保我们在字符串的开头:确定 -
(?=
:让我们检查以下正则表达式是否可以匹配... -
.*
:匹配任意数量的字符->2a
.好吧. -
\d
:不,我们已经结束了.让我们返回一个字符:a
->不,不匹配.返回另一个:2
-> MATCH! -
)
:前瞻结束,匹配成功.我们静止在位置0! -
(?=
:让我们检查以下正则表达式是否可以匹配... -
.*
:匹配任意数量的字符->2a
.好吧. -
[a-z]
:不,我们已经结束了.让我们返回一个字符:a
-> MATCH! -
)
:前瞻结束,匹配成功.我们静止在位置0! -
.*
:匹配任意数量的字符->2a
->匹配! -
$
:让我们看看-我们在字符串的末尾吗?是的我们是! ->比赛! - 嘿,我们已经到了正则表达式的结尾.伟大的.比赛结束!
^
: Make sure we're at the start of the string: OK(?=
: Let's check if the following regex could match....*
: match any number of characters ->2a
. OK.\d
: Nope, we're already at the end. Let's go back one character:a
--> No, doesn't match. Go back another one:2
--> MATCH!)
: End of lookahead, match successful. We're still at position 0!(?=
: Let's check if the following regex could match....*
: match any number of characters ->2a
. OK.[a-z]
: Nope, we're already at the end. Let's go back one character:a
--> MATCH!)
: End of lookahead, match successful. We're still at position 0!.*
: match any number of characters ->2a
--> MATCH!$
: Let's see - are we at the end of the string? Yes, we are! --> MATCH!- Hey, we've reached the end of the regex. Great. Match completed!
这篇关于正则表达式-超前断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!