Going mad on an egrep command (Reg Expressions)

Dear community,

I am trying for several hours now to create an egrep command to grep the number of lines containing a specific text from a text-file but seem to have an error somewhere.

The Textfile contains several thousand lines and has the expression "Lastname" in several lines. Problem is, that there is also expressions like "xLastname" or "abcLastname" in there which I DON'T want to grab.
So the definition of the RegExpression should look like this

EITHER there is no text at all in the line before "Lastname" appears
OR there is Text in the line BUT then a SPACE has to be between the random text and the expression "Lastname"

I tried with ((.+\ )?|(^.))Lastname and ((.+\ )?|(^.))Lastname and ((.+\ )?|[^.])Lastname and ((.+\ )?|[^.])Lastname but it always results in the egrep command finding expressions like "abcLastname".

Where is my mistake? The first part (.+\ ) ("If there is text, there HAS to be a SPACE afterwards") seems to work fine but the "OR there is no text at all" does not seem to work.
Wasn't there a special character that I can use to simply check if whatever comes after it is the FIRST expression/character in the line? I cannot find that information online unfortunately.

Thanks to all of you in advance for your help

Best Regards
Donzo

try egrep -oh (pattern) filename

#example:
Owner@Owner-PC ~
$ egrep -oh '(LastName)' Edit1.txt
LastName
LastName
LastName
LastName
LastName
LastName

Owner@Owner-PC ~
$ cat Edit1.txt
FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOLastName^^^^^^^^FFF
abc LastName ABC
LastName
abc LastName abc

abcLastName
LastNameabc

1 Like

Unfortunately I cannot use that as there is a big load of expressions follwing that I excluded here for purpose of better understanding.

I realized it now after over 3 hours with:

((.+\ )|(\ )|^)Lastname

and it seems to finally work.

But thanks a lot for your effort !

Doesn't .+\ include \ ?
Try

( |^)Lastname

Or the following

^(.* )?Lastname