惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
GRAHAM CLULEY
T
Tenable Blog
Know Your Adversary
Know Your Adversary
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
S
Security Affairs
NISL@THU
NISL@THU
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
Webroot Blog
Webroot Blog
Schneier on Security
Schneier on Security
S
SegmentFault 最新的问题
S
Schneier on Security
G
Google Developers Blog
V
V2EX
C
Check Point Blog
U
Unit 42
Google DeepMind News
Google DeepMind News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
T
The Exploit Database - CXSecurity.com
Recent Announcements
Recent Announcements
M
MIT News - Artificial intelligence
S
Secure Thoughts
博客园 - 司徒正美
Recorded Future
Recorded Future
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
K
Kaspersky official blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
博客园 - 聂微东
N
News and Events Feed by Topic
SecWiki News
SecWiki News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
Recent Commits to openclaw:main
Recent Commits to openclaw:main
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
Project Zero
Project Zero
W
WeLiveSecurity
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
PWC 376 Doubled Words
Bob Lied · 2026-06-04 · via DEV Community

Bob Lied

There are two things that every Perl developer knows:

  1. Parsing HTML with regular expressions is a bad idea.
  2. My situation is unique and exceptional, such that parsing HTML with regular expressions is ingenious and optimal.

Let's see the task. I think you know where this is going.

Task 2: Double Words

You are given a string (which may contain embedded newlines) which is taken from a page on a website. The string will not contain brackets [].

Write a script that will find doubled words (such as “this this”) and highlight (wrap in brackets) each doubled word.

The script should:

  • Work across lines, even finding situations where a word at the end of one line is repeated at the beginning of the next.

  • Find doubled words despite capitalization differences, such as with 'The the...', as well as allow differing amounts of whitespace (spaces, tabs, newlines, and the like) to lie between the words.

  • Find doubled words even when separated by HTML tags. For example, to make a word bold: '...it is <B>very</B> very important...'.

  • Only show lines containing doubled words.

Adapted from Mastering Regular Expressions, Third Edition, by Jeffrey E. F. Friedl

  • Example 1

    • Input: $str = "you're given the job of checking the pages on a\nweb server for doubled words (such as 'this this'), a common problem\nwith documents subject to heavy editing."
    • Output: "web server for doubled words (such as '[this] [this]'), a common problem"
  • Example 2

    • Input: $str = "Find doubled words despite capitalization differences, such as with 'The\nthe...', as well as allow differing amounts of whitespace (spaces,\ntabs, newlines, and the like) to lie between the words."
    • Output: "Find doubled words despite capitalization differences, such as with '[The]\n[the]...', as well as allow differing amounts of whitespace (spaces,"
  • Example 3

    • Input: $str = "to make a word bold: '...it is <B>very</B> very important...'."
    • Output: "to make a word bold: '...it is <B>[very]</B> [very] important...'."
  • Example 4

    • Input: $str = "Perl officially stands for Practical Extraction and Report Language, except when it doesn't."
    • Output: ""
  • Example 5

    • Input: $str = "There's more than one one way to do it.\nEasy things should be easy and hard things should be possible."
    • Output: "There's more than [one] [one] way to do it."

So it begins

The reference to Mastering Regular Expressions seems like a pretty strong hint. Back when I was doing HTML and XML processing, I always favored using a module to parse tagged text (XML::Twig was a particular favorite), but let's take the hint.

A sort of obvious thing to do here is to split the string into words, but it's going to be annoying because of the possibility of HTML tags. And once we break the string up, we'll lose the space and tags that we need to retain for the requested output.

"The string will not contain brackets" is an odd thing to say. But it turns out to be useful, because we only want to print output lines that do contain brackets, so this little clause is actually doing us a favor.

An outline

Let's assume that we can conjure up a regular expression to use with split to extract the words; let's call it $sepRE. We can then compare consecutive pairs of words to find duplication. That solves half the problem, but loses the context in the original string. We need to reproduce the original text, plus highlighting brackets, including all the stuff between words.

Because we have weird habits, we have (more than once) read through all the documentation of split, and so we know that there is a variation in which the function can return both the desired substrings and the separators. To wit, if we enclose the regular expression in parentheses, split will return all the pieces of the string, alternating between separators and substrings. The first piece we need looks like:

my @word = split( /($sepRE)/, $str);

Enter fullscreen mode Exit fullscreen mode

Now the words will be in either the even or odd elements of @word, depending on whether the string started with a separator. We can check for duplicates by skipping along in pairs.

# Take every other word. Skip over a leading separator.
my ($first, $second) = ( $word[0] =~ m/$sepRE/ )
                     ? (1,3) : (0, 2);

while ( $second <= $#word)
{
    my (@w) = ( $word[$first], $word[$second]);

    if ( $w[0] eq $w[1] )
    {
        $word[$first]  =~ s/($w[0])/[$1]/;
        $word[$second] =~ s/($w[1])/[$1]/;
    }
    $first += 2; $second += 2;
}

Enter fullscreen mode Exit fullscreen mode

That marks up the duplicate words, but only in the @word array. We need to face the problem of getting the desired output. To get there, put the @word array back into a single string, and then grep for the lines that contain our newly-inserted brackets.

# Reassemble the string, now with some words possibly bracketed
my $highlighted = join("", @word);

# Output includes only lines where we inserted brackets
return join "\n",
            grep /[\[\]]/, 
                 split(/\n/, $highlighted);

Enter fullscreen mode Exit fullscreen mode

A few minor details

  • Case insensitivity. In our check for duplicates, we need to ignore case differences, so let's compare the lowercase versions of the words: if ( lc($w[0]) eq lc($w[1]) )

  • Punctuation. As shown in Example 2, punctuation surrounding the words should be ignored. Let's whip up a quick function to trim leading and trailing punctuation (the [:punct:] character class is handy for this), and use it before we compare

sub trimPunct($word)
{
    $word =~ s/^[[:punct:]]+//;
    $word =~ s/[[:punct:]]+$//;
    return $word
}
. . .
my (@w) = ( trimPunct($word[$first]),
            trimPunct($word[$second]));

Enter fullscreen mode Exit fullscreen mode

About that regular expression

Time to take care of that regular expression that acts as the word separator. With some experimentation (the regex101 web site is good for that), we arrived at this:

 state $sepRE = 
qr/ \s*     # Possible white space followed by
  (?:       # ( a group of a tag and more white space
   <[^>]*>  #  ... an HTML tag
   \s*      #  ... optional space
  )+        # ) there can be multiple tags
  | \s+     # Or just white space
/x;

Enter fullscreen mode Exit fullscreen mode

Not too bad. Didn't even require look-around assertions. Some notes:

  • state $sepRE = qr/.../ -- This is a constant regular expression, so we can use state to only evaluate it once.
  • qr//x -- The x flag allows us to add formatting and comments to the expression
  • (?:...) -- We want to group, but we don't need the overhead of capturing, so (?:) is a non-capturing group.
  • complicated | \s+ -- Why is the complicated part first? Because the alternatives are evaluated left to right. If \s+ eats up the white space, the expression matches and wouldn't proceed to trying tags.

Okay, here's the whole thing.

sub task($str)
{
    state $sepRE = qr/ \s*     # Possible white space followed by
                     (?:       # ( a group of a tag and more white space
                      <[^>]*>  #  ... an HTML tag
                      \s*      #  ... optional space
                     )+        # ) There can be multiple tags
                     | \s+     # Or just white space
                   /x;

    # Using () in RE includes separators in the array
    my @word = split( /($sepRE)/, $str);

    # Take every other word. Skip over a leading separator.
    my ($first, $second) = ( $word[0] =~ m/$sepRE/ ) ? (1,3) : (0, 2);

    while ( $second <= $#word)
    {
        my (@w) = ( trimPunct($word[$first]), trimPunct($word[$second]));

        if ( lc($w[0]) eq lc($w[1]) )
        {
            $word[$first]  =~ s/($w[0])/[$1]/;
            $word[$second] =~ s/($w[1])/[$1]/;
        }
        $first += 2; $second += 2;
    }

    # Reassemble the string, now with some words possibly bracketed
    my $highlighted = join("", @word);

    # Output includes only lines where we inserted brackets
    return join"\n", grep /[\[\]]/, split(/\n/, $highlighted);
}

Enter fullscreen mode Exit fullscreen mode

And the music for this week's challenge was Double Vision by Foreigner.