Catastrophic backtracking occurred while matching inline base64 stream in Email body

Viewed 45

I am trying to match inline base64 stream inside HTML with below REGEX. But it is throwing Catastrophic backtracking error.

Regex:(?>src=\"data).*?(\">)

Sample data: src="data/image:base64, iVakjsdlfjasldkfjaksjdaksjdflahdsklfjakdsljflkadsfjkjadshfkjahsdfkljahdsflkjadshflkjadshflkjasdhfklashdffasdf"==>

[The stream data is MANY lines]

The REGEX works for few lines of Stream, but throws Catastrophic error for MANY lines of Stream.

Kindly share your thoughts.

1 Answers

Note the problem is in the excessive backtracking caused by the lazy dot pattern applied on a long text. This is a common Java regex issue.

In most cases, you may solve it using a character class instead of a lazy dot.

Here, you may use [^"]* instead of .*?:

String result = text.replaceAll("src=\"data[^\"]*\"", "src=\"\"");

Here,

  • src="data - matches src="data
  • [^"]* - matches any 0 or more chars other than "
  • " - a " double quotation mark.
Related