正则表达式-超前断言 [英] Regex - lookahead assertion

查看:71
本文介绍了正则表达式-超前断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对前瞻性断言(?=)有问题.例如,我有表达:

I have problem with lookahead assertion (?=). For example, I have expression:

/Win(?=2000)/

如果表达式类似于Win2000Win2000fgF,则匹配Win.我有下一个表情:

It match Win, if expression is like Win2000, Win2000fgF. I have next expression:

^(?=.*\d)(?=.*[a-z]).*$

它与数字和小写字母匹配,例如:45dF4Dd.但是我不知道为什么它能工作并匹配所有字符:)我没有字符,在(?=.*\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):

  1. ^:确保我们在字符串的开头:确定
  2. (?=:让我们检查以下正则表达式是否可以匹配...
  3. .*:匹配任意数量的字符-> 2a.好吧.
  4. \d:不,我们已经结束了.让我们返回一个字符:a->不,不匹配.返回另一个:2-> MATCH!
  5. ):前瞻结束,匹配成功.我们静止在位置0!
  6. (?=:让我们检查以下正则表达式是否可以匹配...
  7. .*:匹配任意数量的字符-> 2a.好吧.
  8. [a-z]:不,我们已经结束了.让我们返回一个字符:a-> MATCH!
  9. ):前瞻结束,匹配成功.我们静止在位置0!
  10. .*:匹配任意数量的字符-> 2a->匹配!
  11. $:让我们看看-我们在字符串的末尾吗?是的我们是! ->比赛!
  12. 嘿,我们已经到了正则表达式的结尾.伟大的.比赛结束!
  1. ^: Make sure we're at the start of the string: OK
  2. (?=: Let's check if the following regex could match...
  3. .*: match any number of characters -> 2a. OK.
  4. \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!
  5. ): End of lookahead, match successful. We're still at position 0!
  6. (?=: Let's check if the following regex could match...
  7. .*: match any number of characters -> 2a. OK.
  8. [a-z]: Nope, we're already at the end. Let's go back one character: a --> MATCH!
  9. ): End of lookahead, match successful. We're still at position 0!
  10. .*: match any number of characters -> 2a --> MATCH!
  11. $: Let's see - are we at the end of the string? Yes, we are! --> MATCH!
  12. Hey, we've reached the end of the regex. Great. Match completed!

这篇关于正则表达式-超前断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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