I try to make a regex (important that ist a regex because i need it for fail2ban) to match when the receiver and the sender are the same person:
echo "from=<test@test.ch> to=<test@test.ch>" | grep -E -o '([^=]*s)[ ]*1'
What am I doing wrong ?
Advertisement
Answer
You might use a pattern to match the format of the string between the brackets with a backreference to that capture.
from(=<[^s@<>]+@[^s@<>]+>)s*to1
Explanation
from
Match literally(
Capture group 1=<
Match literally[^s@<>]+
Match 1+ times any char except a whitespace char or@
<
>
@
Match literally[^s@<>]+
Again match 1+ times any char except a whitespace char or@
<
>
>
Match literally
)
Close group 1s*to1
Match 0+ whitespace chars,to
and the backreference to group 1
Use grep -P
instead of -E
for Perl compatible regular expressions.
For example
echo "from=<test@test.ch> to=<test@test.ch>" | grep -oP 'from(=<[^s@<>]+@[^s@<>]+>)s*to1'
A bit broader match could be capturing what is between the brackets
[^=s]+(=<[^<>]+>)s*[^=s]+1