Menu

Why Regex Fails at HTML Translation (And a Production BeautifulSoup Script That Doesn't)
📰

Why Regex Fails at HTML Translation (And a Production BeautifulSoup Script That Doesn't)

DEV Community: html·Aleksey Kulakov·11 days ago
#kHBvqpVp
#devto2#devto#dev#node#translation
Long article (849 words) — no AI summary yet.
Reading 0:00
15s threshold

Your translation script changes href="/help" into a translated phrase, splits “Read the shipping policy” around an inline link, and mangles {{ first_name }} . The common cause is treating HTML as text with boundaries a regular expression can recognize reliably. It cannot: attribute values, script content, and text between inline elements all have different structural roles.

Problem

Consider a shortcut that translates text inside quotation marks:

html = re . sub ( r '"([^"]+)"' , translate , html )

Enter fullscreen mode

Exit fullscreen mode

That expression has no way to tell whether a quoted string is an accessible label, a URL, a class name, a JavaScript value, or part of a template expression. A different pattern that targets text between tags has the opposite problem: inline markup divides a sentence into multiple matches. The phrase in <p>Read the <a href="/help">shipping policy</a> before ordering.</p> is not one uninterrupted text string in the source.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.