Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

regex - Explanation of Lookaheads in This Regular Expression

I understand regular expressions reasonably well, but I don't get to make use of them often enough to be an expert. I ran across a regular expression that I am using to validate password strength, but it contains some regex concepts I am unfamiliar with. The regex is:

^(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{6,}$

and in plain English it means that the string must contain at least one lowercase character, one uppercase character, and one number, and the string must be at least six characters long. Can anyone break this down for me to explain how this pattern actually describes that rule? I see a start of string char ^ and an end of string char $, three groups with lookaheads, a match any character . and a repetition {6,}.

Thanks to any regex guru who can help me get my head around this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Under normal circumstances, a piece of a regular expression matches a piece of the input string, and "consumes" that piece of the string. The next piece of the expression matches the next piece of the string, and so on.

Lookahead assertions don't consume any of the string, so your three lookahead assertions:

  • (?=.*d)
  • (?=.*[a-z])
  • (?=.*[A-Z])

each mean "This pattern (anything followed by a digit, a lowercase letter, an uppercase letter, respectively) must appear somewhere in the string", but they don't move the current match position forwards, so the remainder of the expression:

  • .{6,}

(which means "six or more characters") must still match the whole of the input string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...