mgabriel
mgabriel

Reputation: 155

postfix pcre Regex to match and replace substring

I'm using Postfix MTA and get important mails in from a broken MTA (which I can't fix because it's not under my control), which sends in the following format:

RCPT TO: <+49 (681) 12345678>

What I need is:

RCPT TO: 4968112345678

So I am looking for a regex, which first checks if the string begins with "RCPT TO:" and if this is true, it needs to remove all special characters after it, so that only [a-zA-Z0-9] are left.

Postfix ships an example for such regex'es:

# Work around clients that send RCPT TO:<'user@domain'>.
# WARNING: do not lose the parameters that follow the address.
#/^RCPT\s+TO:\s*<'([^[:space:]]+)'>(.*)/     RCPT TO:<$1>$2

But after several hours I am unable to adapt it to my needs.

Thanks in advance, Marco

Upvotes: 1

Views: 6990

Answers (2)

stefano
stefano

Reputation: 263

Try: /[^RCPT\sTO\:\s]([a-zA-Z0-9]+)/ filter out all the alphanumeric values resulting in 49 681 12345678. [1].

Another better way is blacklisting all the unwanted chars could also be an option, but doesn't sound optimal. /([^<+\)\(>]+)/ results in RCPT TO: 49 681 12345678. [2]

Or Maybe the best option is to capture any word character (letter, number, underscore) /(\w+|:)/ resulting in RCPT TO: 49 681 12345678. [3]

All of this is tested with rubular and I don't know about Postfix MTA. But i hope this helps.

permalinks:

  1. http://www.rubular.com/r/Uapn2m52yk
  2. http://www.rubular.com/r/015iyaNG3T
  3. http://www.rubular.com/r/mmJZBNbH99

Upvotes: 1

citrin
citrin

Reputation: 745

It seems to be, that it is not possible to strip any combination of non-alphanumeric characters in generic case. But for addresses like given in example this regexp should be sufficient:

/^[^a-z0-9]*([a-z0-9]+)[^a-z0-9]*([a-z0-9]+)[^a-z0-9]*([a-z0-9]+)$/     $1$2$3

You can test regexp maps via postmap command:

$ postmap -q "+49 (681) 12345678" pcre:/path/to/regexp_map
4968112345678

To use this regexp map add to postfix config

canonical_maps = prce:$config_directory/regexp_map

Read ADDRESS_REWRITING_README about canonical_maps.

Upvotes: 4

Related Questions