我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
通常点匹配除换行符以外的任何字符。
因此,如果。*不起作用,设置“点也匹配换行符”选项(或使用(?s).*)。
如果您正在使用JavaScript,它没有“dotall”选项,请尝试[\s\ s]*。这意味着“匹配任意数量的空白或非空白字符”——有效地“匹配任何字符串”。
另一个只适用于JavaScript的选项是[^]*,它也匹配任何字符串。但是[\s\ s]*似乎使用得更广泛,可能是因为它更便于携带。
使用.*,并确保您使用的实现相当于单行,以便在行尾匹配。
这里有一个很好的解释-> http://www.regular-expressions.info/dot.html
<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>
http://sandbox.phpcode.eu/g/b2243.php
(.*?)不适合我。我试图匹配注释周围的/* */,其中可能包含多行。
试试这个:
([a]|[^a])
这个正则表达式匹配a或除a之外的任何东西,当然,它意味着匹配所有东西。
顺便说一句,在我的情况下,/\*([a]|[^a])*/匹配C风格的注释。
感谢@mpen提供了一个更简洁的方式。
[\s\S]
选择并记住以下1个!!:)
[\s\S]*
[\w\W]*
[\d\D]*
解释:
\s:没有空白
\w:字\w:不字
\d:数字\d:不是数字
(如果你想要1个或更多字符[而不是0个或更多],可以将*替换为+)。
附加编辑:
如果你想匹配一行中的所有内容,你可以使用这个:
[^\n]+
解释:
^:不
\ n: linebreak
+:表示1个字符或更多
对于JavaScript,最好和最简单的答案似乎是/.\*/。
正如其他人所建议的/(.*?)/也可以,但是/。\*/更简单。()里面的图案是不需要的,就我所见也没有结局?匹配任何内容(包括空字符串)
的办法:
/[\s\ s]/不匹配空字符串,因此不是解决方案。 /[\s\ s]\*/ DOES也匹配空字符串。但它有一个问题:如果你在代码中使用它,那么你就不能注释掉这样的代码,因为*/被解释为注释结束。
/([\s\ s]\*)/可以工作并且不存在注释问题。但是它比/.*/要长,理解起来也更复杂。
我建议使用/(?=.*…)/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进行测试
如果你使用JavaScript, ES2018添加了/s (dotAll)标志。带有/s标志的点。将匹配任何字符,包括换行符。
游戏机log(“line_1 \ nline_2”。match (/ + / 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. |
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 "
一个选项是空正则表达式,在JavaScript中表示为/(?:)/。(也可以使用new RegExp())。逻辑上,一个空正则表达式应该匹配在任何位置包含“空”的字符串——当然是所有的字符串。
请参阅这个SO问题和这篇博客文章进行讨论和更多细节。