开发者

Regular expression to match text that doesn't start with substring?

开发者 https://www.devze.com 2022-12-24 03:29 出处:网络
I have text with file names scattered throughout. The filenames appear in the text like this: test.txt|

I have text with file names scattered throughout. The filenames appear in the text like this:

|test.txt|
|usr01.txt|
|usr02.txt|
|foo.txt|

I want to match the filenames that don't start with usr. I came up with (?<=\|).*\.txt(?=\|) to match the filenames, but it doesn't exc开发者_Go百科lude the ones starting with usr. Is this possible with regular expressions?


(?<=\|)(?!usr).*\.txt(?=\|)

You were nearly there :)

Now you have a positive lookbehind, and a positive and negative lookahead.


With python

>>> import re
>>>
>>> x="""|test.txt|
... |usr01.txt|
... |usr02.txt|
... |foo.txt|
... """
>>>
>>> re.findall("^\|(?!usr)(.*?\.txt)\|$",x,re.MULTILINE)
['test.txt', 'foo.txt']


grep -v "^|usr" file

awk '!/^\|usr/' file

sed -n '/^|usr/!p' file
0

精彩评论

暂无评论...
验证码 换一张
取 消