正则表达式 - 如何匹配连续四位数以外的所有内容?

时间:2015-07-01 18:54:56

标签: regex

使用正则表达式,如何匹配连续四位数以外的所有内容?以下是我可能正在使用的示例文本:

foo1234bar
baz      1111bat
asdf 0000 fdsa
a123b

匹配可能如下所示:

"foo", "bar", "baz      ", "bat", "asdf ", " fdsa", "a123b"

以下是我自己提出的一些正则表达式,它们无法捕获我需要的所有内容:

[^\d]+            (this one includes a123b)
^.*(?=[\d]{4})    (this one does not include the line after the 4 digits)
^.*(?=[\d]{4}).*  (this one includes the numbers)

关于如何在四位数序列之前和之后获得匹配的任何想法?

3 个答案:

答案 0 :(得分:4)

您尚未指定自己的应用语言,但实际上每种应用语言都有分割功能,如果您在\d{4}分割,您将获得所需的内容。

例如在java中:

String[] stuffToKeep = input.split("\\d{4}");

答案 1 :(得分:1)

您可以使用否定前瞻:

(?!\b\d{4}\b)(\b\w+\b)

Demo

答案 2 :(得分:0)

Python 中,以下内容与您想要的非常接近:

In [1]: import re

In [2]: sample = '''foo1234bar
   ...: baz      1111bat
   ...: asdf 0000 fdsa
   ...: a123b'''

In [3]: re.findall(r"([^\d\n]+\d{0,3}[^\d\n]+)", sample)
Out[3]: ['foo', 'bar', 'baz      ', 'bat', 'asdf ', ' fdsa', 'a123b']
相关问题