繁体   English   中英

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

[英]Regex - How do you match everything except four digits in a row?

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

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)

关于如何在四位数序列前后进行匹配的任何想法?

您尚未指定应用程序语言,但是实际上每种应用程序语言都具有拆分功能,如果在\\d{4}上进行拆分,您将获得所需的内容。

例如在Java中:

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

您可以使用否定的前瞻:

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

演示

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM