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

Regex:我买了_____羊。

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

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


当前回答

我建议使用/(?=.*…)/g

例子

const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true

const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true

const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true

const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text

使用regex101进行测试

其他回答

(.*?)不适合我。我试图匹配注释周围的/* */,其中可能包含多行。

试试这个:

([a]|[^a])

这个正则表达式匹配a或除a之外的任何东西,当然,它意味着匹配所有东西。

顺便说一句,在我的情况下,/\*([a]|[^a])*/匹配C风格的注释。

感谢@mpen提供了一个更简洁的方式。

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

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

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

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.

使用.*,并确保您使用的实现相当于单行,以便在行尾匹配。

这里有一个很好的解释-> http://www.regular-expressions.info/dot.html

一个选项是空正则表达式,在JavaScript中表示为/(?:)/。(也可以使用new RegExp())。逻辑上,一个空正则表达式应该匹配在任何位置包含“空”的字符串——当然是所有的字符串。

请参阅这个SO问题和这篇博客文章进行讨论和更多细节。