且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可选的空白正则表达式

更新时间:2023-02-21 19:43:15

如果可以允许空格,请添加\s?.

Add a \s? if a space can be allowed.

\ s 代表空白

?说前面的字符可能出现一次或不发生.

? says the preceding character may occur once or not occur.

如果允许多个空格并且是可选空格,请使用\s*.

If more than one spaces are allowed and is optional, use \s*.

* 说前面的字符可以出现零次或多次.

* says preceding character can occur zero or more times.

'#<a href\s?="(.*?)" title\s?="(.*?)"><img alt\s?="(.*?)" src\s?="(.*?)"[\s*]width\s?="150"[\s*]height\s?="(.*?)"></a>#'

在属性名称和=之间留有一个可选空格.

allows an optional space between attribute name and =.

如果您还希望在=后面添加一个可选空格,请在其后也添加一个\s?.

If you want an optional space after the = also, add a \s? after it also.

同样,无论您在何处有可选字符,如果最大出现次数是 1 ,则可以使用?;如果最大出现次数是无限的,则可以使用*(在可选字符之后).

Likewise, wherever you have optional characters, you can use ? if the maximum occurrence is 1 or * if the maximum occurrence is unlimited, following the optional character.

您的实际问题是[\s*],由于[]中包含的字符是字符类,导致出现空白 a * .字符类允许一次其任何成员出现(因此从中删除*),并且如果在]任何字符之后附加了量词(?+*等)字符类中的字符可以根据量词出现.

And your actual problem was [\s*] which causes occurrence of a whitespace or a * as characters enclosed in [ and ] is a character class. A character class allows occurrence of any of its members once (so remove * from it) and if you append a quantifier (?, +, * etc) after the ] any character(s) in the character class can occur according to the quantifier.