使用grep regex匹配任意位数 [英] Matching arbitrary number of digits using grep regex
问题描述
我有一个文件,其中包含类似于以下内容的行
I've got a file that has lines in it that look similar as follows
data
datalater
983290842
Data387428later
datafhj893724897290384later
4329804928later
我想要做的是使用正则表达式来匹配以数据开头,以以后结尾且中间有数字的任何行.到目前为止,这是我构想的:
What I am looking to do is use regex to match any line that starts with data and ends with later AND has numbers in between. Here is what I've concocted so far:
^[D,d]ata[0-9]*later$
但是,输出包括所有数据行.我想我可以通过管道输出grep -v datalater,但是我觉得一个表达式应该可以解决问题.
However the output includes all datalater lines. I suppose I could pipe the output and grep -v datalater, but I feel like a single expression should do the trick.
推荐答案
使用+
代替*
.
+
至少匹配上述一个或多个.
*
匹配零个或多个.
+
matches at least one or more of the preceding.
*
matches zero or more.
^[Dd]ata[0-9]+later$
在grep中,您需要转义+
,我们可以使用\d
这是一个字符类并匹配一位数字.
In grep you need to escape the +
, and we can use \d
which is a character class and matches single digits.
^[Dd]ata\d\+later$
在示例文件中,您还会有一行:
In you example file you also have a line:
datafhj893724897290384later
由于数据和数字之间存在字母,因此当前无法匹配.我们可以通过添加[^0-9]*
来解决此问题,以匹配数据后直到数字的所有内容.
This currently will not be matched due to there being letters in-between data and the numbers. We can fix this by adding a [^0-9]*
to match anything after data until the digits.
我们的最终命令将是:
grep '^[Dd]ata[^0-9]*\d\+later$' filename
这篇关于使用grep regex匹配任意位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!