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

Regex:我买了_____羊。

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

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


当前回答

我用这个:(.|\n)+对我来说就像一个魅力!

其他回答

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

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

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

Regex: /I bought.*sheep./ Matches - the whole string till the end of line I bought sheep. I bought a sheep. I bought five sheep. Regex: /I bought(.*)sheep./ Matches - the whole string and also capture the sub string within () for further use I bought sheep. I bought a sheep. I bought five sheep. I boughtsheep. I bought a sheep. I bought fivesheep. Example using Javascript/Regex 'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[0]; Output: "I bought sheep. I bought a sheep. I bought five sheep." 'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[1]; Output: " sheep. I bought a sheep. I bought five "

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

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

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

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

因为。查找单个字符,换行符或行结束符除外。

所以,要匹配任何东西,你可以这样使用:(.|\n)*?

希望能有所帮助!