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

Regex:我买了_____羊。

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

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


当前回答

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

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

其他回答

选择并记住以下1个!!:)

[\s\S]*
[\w\W]*
[\d\D]*

解释:

\s:没有空白

\w:字\w:不字

\d:数字\d:不是数字

(如果你想要1个或更多字符[而不是0个或更多],可以将*替换为+)。

附加编辑:

如果你想匹配一行中的所有内容,你可以使用这个:

[^\n]+

解释:

^:不

\ n: linebreak

+:表示1个字符或更多

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

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 bought (.* )?sheep

甚至

I bought .*sheep

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

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

希望能有所帮助!

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

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