Taking that apart, we are looking for a spot between two characters where a space should be inserted. We have a positive requirement for what comes before the spot (that's the (?<=...)) and a negative requirement for what comes after the spot. The after condition is simple. If there is a whitespace character (I'm guessing that you mean to include tab, newline, etc., based on your use of \S) this spot can be skipped.$s =~ s/(?<=(?<!\d(?=[.,]\d))\p{P})(?!\s)/ /g;
The before condition is essentially (?<=\pP) with an additional condition. \pP matches any punctuation character. These are:
Plus several more unicode characters if you have utf8 data. If you mean a more restricted set of characters, use a character class like [.!,;] or whatever.$ perl -wle'use charnames (); for (0..255) { chr($_) =~ /\pP/ and prin +t chr($_) ," ($_): ", charnames::viacode($_) }' ! (33): EXCLAMATION MARK " (34): QUOTATION MARK # (35): NUMBER SIGN % (37): PERCENT SIGN & (38): AMPERSAND ' (39): APOSTROPHE ( (40): LEFT PARENTHESIS ) (41): RIGHT PARENTHESIS * (42): ASTERISK , (44): COMMA - (45): HYPHEN-MINUS . (46): FULL STOP / (47): SOLIDUS : (58): COLON ; (59): SEMICOLON ? (63): QUESTION MARK @ (64): COMMERCIAL AT [ (91): LEFT SQUARE BRACKET \ (92): REVERSE SOLIDUS ] (93): RIGHT SQUARE BRACKET _ (95): LOW LINE { (123): LEFT CURLY BRACKET } (125): RIGHT CURLY BRACKET ¡ (161): INVERTED EXCLAMATION MARK « (171): LEFT-POINTING DOUBLE ANGLE QUOTATION MARK · (183): MIDDLE DOT » (187): RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK ¿ (191): INVERTED QUESTION MARK
The additional condition is (?<!\d(?=[.,]\d)): this stipulates that what comes before the punctuation should not match \d(?=[.,]\d); that is a single digit, where the digit is followed by a period or comma and another digit. Note that that lookahead is actually escaping the bounds of the outer lookbehind, but that is perfectly ok to do.
Update: added actual character to punctuation table
Update: weird. backtick (GRAVE ACCENT) isn't considered punctuation
In reply to Re: Regex to add space after punctuation sign
by ysth
in thread Regex to add space after punctuation sign
by dda
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |