我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
当前回答
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 "
其他回答
使用.*,并确保您使用的实现相当于单行,以便在行尾匹配。
这里有一个很好的解释-> http://www.regular-expressions.info/dot.html
我用这个:(.|\n)+对我来说就像一个魅力!
(.*?)不适合我。我试图匹配注释周围的/* */,其中可能包含多行。
试试这个:
([a]|[^a])
这个正则表达式匹配a或除a之外的任何东西,当然,它意味着匹配所有东西。
顺便说一句,在我的情况下,/\*([a]|[^a])*/匹配C风格的注释。
感谢@mpen提供了一个更简洁的方式。
[\s\S]
因为。查找单个字符,换行符或行结束符除外。
所以,要匹配任何东西,你可以这样使用:(.|\n)*?
希望能有所帮助!
对于JavaScript,最好和最简单的答案似乎是/.\*/。
正如其他人所建议的/(.*?)/也可以,但是/。\*/更简单。()里面的图案是不需要的,就我所见也没有结局?匹配任何内容(包括空字符串)
的办法:
/[\s\ s]/不匹配空字符串,因此不是解决方案。 /[\s\ s]\*/ DOES也匹配空字符串。但它有一个问题:如果你在代码中使用它,那么你就不能注释掉这样的代码,因为*/被解释为注释结束。
/([\s\ s]\*)/可以工作并且不存在注释问题。但是它比/.*/要长,理解起来也更复杂。