Steven
Steven

Reputation: 2558

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

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 exclude the ones starting with usr. Is this possible with regular expressions?

Upvotes: 3

Views: 5199

Answers (3)

ghostdog74
ghostdog74

Reputation: 342313

grep -v "^|usr" file

awk '!/^\|usr/' file

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

Upvotes: -1

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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

You were nearly there :)

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

Upvotes: 7

YOU
YOU

Reputation: 123791

With python

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

Upvotes: 1

Related Questions