正则表达式中的^.*和.*$分别代表什么意思?

42

有人可以解释一下这些字符的含义吗?我查过它们,但好像还是不理解。

整个正则表达式是:

/^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/

基本上就是正则表达式的开始和结束字符。


7
大家给出的答案都是正确的。我想补充一点,它们是无用的。/^.*(…).*$//(…)/ 是完全相同的。 - SteeveDroz
为什么我们需要在正则表达式的开头和结尾使用“/”? - vikramvi
1
如果是JS,它表示正则表达式的开始和结束,就像字符串的引号一样。 - tnagy.adam
8个回答

87
  • .表示“任何字符”。
  • *表示“任意数量的该字符”。
  • .*因此表示任意长度的任意字符串。
  • ^表示字符串的开头。
  • $表示字符串的结尾。

正则表达式意味着:可以在被搜索的字符串中,(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])表达式之间有任意数量的字符。


你能推荐一个好的正则表达式速查表吗?另外,为什么OP在开头和结尾加上“/”? - vikramvi
如果我使用“.”,如何排除空格。 - Pawan Deore
".+"的含义是什么,这与其他有何不同?" - Paris

26
^.* //Start of string followed by zero or more of any character (except line break)

.*$ //Zero or more of any character (except line break) followed by end of string

所以当你看到这个时...

(?=.*[@#$%^&+=]).*$

这段代码允许除了换行符以外的任何字符出现在(?=.*[@#$%^&+=])与字符串末尾之间。

要证明.不匹配任何字符,请尝试以下代码:

/./.test('\n');  is false

要匹配任何字符,您需要使用类似于 [\s\S] 的表达式。

/[\s\S]/.test('\n') is true

11

主要文档:http://www.php.net/manual/zh/reference.pcre.pattern.syntax.php

/^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/
12345   6         7                                  89

1 - start of pattern, can be almost any character, and must have a matching character at the END of the pattern (see #9 below)
2 - anchors the pattern to the start of a line of text
3 - `.` matches any character
4 - a modifier, "0 or more of whatever came before"
  - `.*` means "0 or more of ANY characters"
5 - A positive lookahead assertion: http://www.php.net/manual/en/regexp.reference.assertions.php
6 - A repetition indictor: http://www.php.net/manual/en/regexp.reference.repetition.php
  - `{8,}` = "at least 8 of whatever came previously"
  - `.{8,}` = "at least 8 'any' characters"
7 - A character class: http://www.php.net/manual/en/regexp.reference.character-classes.php
  - `[a-z]` - any one character in the range 'a' - 'z' (the lower case alphabet)
8 - anchors the pattern to the end of the line
9 - end of the pattern, must match character used in #1 above.

幸好没有第十个提示要暗示。 ;) 非常好的答案! - Till Helge

5

这个正则表达式匹配行首(^)后面的任意字符(.*):

^.*

这段内容的意思是:$表示任意字符之后的行尾。其中 .* 表示任意字符的匹配。
.*$

4

^ 匹配字符串的开头

$ 匹配字符串的结尾

.* 代表任意数量的字符


谢谢回答。为什么在末尾要重复 .*? - logistef
因为在最后一个“特定”匹配之后,文本行中可能会有字符。 - Till

0

还有一些可能会在未来对你有帮助的内容:

.*$

给定字符串"1",将匹配两次:

如果你想知道为什么,那是因为它消耗了所有字符,但又没有匹配任何内容。因此,空字符串也是一种匹配。


0

这看起来像是一个典型的密码验证正则表达式,但它有一些错误。首先,在开头的.*不应该出现。如果任何一个前瞻在字符串的开头没有成功,那么在下一个位置、下一个位置等再次应用它们就没有意义了。

其次,虽然正则表达式确保了这三种字符中的每一种都存在,但它并没有说其他部分的字符串。这可能是一个故意的选择,但人们通常会尝试确保只有这些类型的字符存在。在这种情况下,您需要将第一个前瞻从(?=.{8,})更改为(?=[A-Za-z@#$%^&+=]{8,}$)

最终结果:

/^(?=[A-Za-z@#$%^&+=]{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/

-2

^ 在正则表达式的开头用于不考虑跟在此符号后面的元素。

例如:

String s= Test1ng-345Gt=code-Q!

regEx模式 -> "[^A-Za-z0-9]" 将给出输出-> "-=-!"

检查这个网站很有帮助 -> https://regex101.com/


但这不是OP使用它的方式-请看其他所有答案。 - Hans Kesting
但这并不是OP使用它的方式 - 看看其他所有的回答。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接