我如何使一个表达式匹配绝对任何东西(包括空白)?例子:

Regex:我买了_____羊。

火柴:我买了羊。我买了一只羊。我买了五只羊。

我尝试使用(.*),但似乎没有工作。


当前回答

<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>

http://sandbox.phpcode.eu/g/b2243.php

其他回答

对于JavaScript,最好和最简单的答案似乎是/.\*/。

正如其他人所建议的/(.*?)/也可以,但是/。\*/更简单。()里面的图案是不需要的,就我所见也没有结局?匹配任何内容(包括空字符串)


的办法:

/[\s\ s]/不匹配空字符串,因此不是解决方案。 /[\s\ s]\*/ DOES也匹配空字符串。但它有一个问题:如果你在代码中使用它,那么你就不能注释掉这样的代码,因为*/被解释为注释结束。

/([\s\ s]\*)/可以工作并且不存在注释问题。但是它比/.*/要长,理解起来也更复杂。

<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>

http://sandbox.phpcode.eu/g/b2243.php

通常点匹配除换行符以外的任何字符。

因此,如果。*不起作用,设置“点也匹配换行符”选项(或使用(?s).*)。

如果您正在使用JavaScript,它没有“dotall”选项,请尝试[\s\ s]*。这意味着“匹配任意数量的空白或非空白字符”——有效地“匹配任何字符串”。

另一个只适用于JavaScript的选项是[^]*,它也匹配任何字符串。但是[\s\ s]*似乎使用得更广泛,可能是因为它更便于携带。

/。如果没有换行符,*/效果很好。如果它必须匹配换行符,这里有一些解决方案:

Solution Description
/.*/s /s (dot all flag) makes . (wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more.
/[\s\S]*/ \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s) will match anything that is not a whitespace character. * (asterisk) will match all occurrences of the character set (Encapsulated by []). Read more.

老实说,很多答案都是旧的,所以我发现,如果你只是简单地测试任何字符串,不管字符内容“/。*/i"将充分获得所有内容。