如何创建一个能够匹配任意内容(包括空格)的表达式?
例子:
正则表达式: 我买了_____只羊。
匹配结果: 我买了羊。我买了一只羊。我买了五只羊。
我尝试使用 (.*)
,但是好像不起作用。
如何创建一个能够匹配任意内容(包括空格)的表达式?
例子:
正则表达式: 我买了_____只羊。
匹配结果: 我买了羊。我买了一只羊。我买了五只羊。
我尝试使用 (.*)
,但是好像不起作用。
(.*?)
对我没有用。我正在尝试匹配被 /* */
包围的注释,这些注释可能包含多行。
试试这个:
([a]|[^a])
a
或者除了a以外的任何字符
。确切地说,它意味着匹配所有内容。/\*([a]|[^a])*/
匹配C风格的注释。[\s\S]
[\s\S]
-- 即匹配空格和非空格。 - mpenRegex:
/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 five
sheep.
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 "
<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>
/.*/i
不匹配换行符。另外,/i
(忽略大小写标志)是多余的。 - Sam/(?=.*...)/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 进行测试
我尝试了一下,不知怎么地就成功了:
[^\000]+
.*
应该可以工作。你能复制粘贴你实际的代码吗? - Jacob Eggers(?s:.)
- 内联修饰符组 匹配包括换行符在内的任何字符。在您的情况下,它应该是这样的:(?s:.*?)
。摘自 Wiktor Stribiżew 的答案。 - Dmitriy Zub