我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
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进行测试
其他回答
一个选项是空正则表达式,在JavaScript中表示为/(?:)/。(也可以使用new RegExp())。逻辑上,一个空正则表达式应该匹配在任何位置包含“空”的字符串——当然是所有的字符串。
请参阅这个SO问题和这篇博客文章进行讨论和更多细节。
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, ES2018添加了/s (dotAll)标志。带有/s标志的点。将匹配任何字符,包括换行符。
游戏机log(“line_1 \ nline_2”。match (/ + / s))
注意:目前还不是所有浏览器都支持它。
<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>
http://sandbox.phpcode.eu/g/b2243.php
我建议使用/(?=.*…)/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进行测试