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

I have text with file names scattered around the world. File names appear in the text as follows:

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

I want to match file names that do not start with usr. I came up (?<=\|).*\.txt(?=\|)with a file name match, but that doesn't exclude those that start with usr. Is this possible with regular expressions?

+3
source share
3 answers
(?<=\|)(?!usr).*\.txt(?=\|)

You were almost there :)

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

+7
source

With python

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

awk '!/^\|usr/' file

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

Source: https://habr.com/ru/post/1737876/


All Articles