#!/usr/bin/perl use 5.016; use strict; use warnings; # 1040996 my @strs = ("foo bar &gt;lt;amp; blivitz", "FOO BAR BLIVITZ, >apos; "sect; ", "no entities here", "But there are ¢pound; entities for 'cent' and 'pound' here.", ); for my $str(@strs) { if ( $str =~ /(&[^ ]+)/ ) { # match any ampersand followed by one or # more NON-spaces (aka \S; see below) my $found = $1; say "DEBUG: found semicolon(s) at |$found| in \"$str\""; if ($str =~ / [^&;]*? # anything that's neither "&" nor ";" (&.+) # followed by an ampersand and multiple chars (?!\S) # until prev capture is followed by something # NOT-a-space ("negative lookahead") /gx ) { # globally, extended notation, end conditions, begin actions my $substr = $1; say "\$substr: $substr\n"; (my $fixed = $substr ) =~ s/(;)([a-z])/$1&$2/g; say "\$fixed: $fixed \n"; } } else { say "\n\t No html entities found.\n"; } } =head C:\>1040996.pl DEBUG: found semicolon(s) at |&gt;lt;amp;| in "foo bar &gt;lt;amp; blivitz" $substr: &gt;lt;amp; blivitz $fixed: &><& blivitz DEBUG: found semicolon(s) at |>apos;| in "FOO BAR BLIVITZ, >apos; "sect; " $substr: >apos; "sect; $fixed: >' "§ No html entities found. DEBUG: found semicolon(s) at |¢pound;| in "But there are ¢pound; entities for 'cent' and 'pound' here." $substr: ¢pound; entities for 'cent' and 'pound' here. $fixed: ¢£ entities for 'cent' and 'pound' here. =cut