正则表达式 - 匹配任何内容

453

如何创建一个能够匹配任意内容(包括空格)的表达式?
例子:

正则表达式: 我买了_____只羊。

匹配结果: 我买了羊。我买了一只羊。我买了五只羊。

我尝试使用 (.*),但是好像不起作用。


51
.* 应该可以工作。你能复制粘贴你实际的代码吗? - Jacob Eggers
4
你用的是什么编程语言? - Ziggy
16
一个点号不能匹配换行符。 - fy_iceworld
4
无法正常工作的原因是在"bought"和"sheep"之间有两个空格。所以"I bought sheep"是错误的,而"I bought sheep"是正确的。 - user11955706
1
(?s:.) - 内联修饰符组 匹配包括换行符在内的任何字符。在您的情况下,它应该是这样的:(?s:.*?)。摘自 Wiktor Stribiżew答案 - Dmitriy Zub
18个回答

3

(.*?) 对我没有用。我正在尝试匹配被 /* */ 包围的注释,这些注释可能包含多行。

试试这个:

([a]|[^a])

这个正则表达式匹配a或者除了a以外的任何字符。确切地说,它意味着匹配所有内容。
顺便提一句,在我的情况下,/\*([a]|[^a])*/匹配C风格的注释。
感谢@mpen提供更简洁的方法。
[\s\S]

2
在JS中最常见的方法是[\s\S] -- 即匹配空格和非空格。 - mpen

3
  1. Regex:

    /I bought.*sheep./
    

    Matches - the whole string till the end of line

    I bought sheep. I bought a sheep. I bought five sheep.

  2. 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 "


0

0
说实话,很多答案都过时了,所以我发现如果你只是用 "/.*/i" 测试任何字符串,无论字符内容如何,都可以得到所有东西。

1
/.*/i 不匹配换行符。另外,/i(忽略大小写标志)是多余的。 - Sam

0

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

有关讨论和更多详细信息,请参见此SO问题此博客文章


0
我建议使用/(?=.*...)/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 进行测试


-1

我尝试了一下,不知怎么地就成功了:

    [^\000]+

1
不错,但你必须提供一个答案的解释,并且你必须理解它——你的正则表达式匹配一个或多个不是字符代码0x000即null的字符。我猜在某些情况下很有用,但对于这个主题来说基本上无关紧要。 - Oly Dungey

-3
我使用这个:(.|\n)+ 对我来说非常好用!

3
除非您必须在ElasticSearch的正则表达式中使用此模式,否则请勿使用。它会导致大量回溯步骤,并引起堆栈溢出问题。此外,在此处已经提到过这个解决方案。 - Wiktor Stribiżew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接