Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
There's more than one way to do things
 
PerlMonks  

Re: Regex to add space after punctuation sign

by ysth (Canon)
on Jan 08, 2004 at 09:19 UTC ( #319757=note: print w/ replies, xml ) Need Help??


in reply to Regex to add space after punctuation sign

Something like:

$s =~ s/(?<=(?<!\d(?=[.,]\d))\p{P})(?!\s)/ /g;
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.

The before condition is essentially (?<=\pP) with an additional condition. \pP matches any punctuation character. These are:

$ 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
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.

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


Comment on Re: Regex to add space after punctuation sign
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://319757]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (15)
As of 2014-04-18 11:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (466 votes), past polls