I would like to insert spaces between characters in word, but only for word with at least 2 upper case characters. I can use regex.
For example: "This is simple SEnTeNCE with a FEW word." -> "This is simple S E n T e N C E with a F E W word."
I would like to insert spaces between characters in word, but only for word with at least 2 upper case characters. I can use regex.
For example: "This is simple SEnTeNCE with a FEW word." -> "This is simple S E n T e N C E with a F E W word."
A way with PHP/PCRE:
$pattern = '~(?:\b(?=(?:\w*[A-Z]){2})|(?!^)\G)\w\B\K~';
$text = preg_replace($pattern, ' ', $text);
pattern details:
(?: # non capturing group: begin with:
\b # a word boundary
(?=(?:\w*[A-Z]){2}) # followed by a word with two uppercase letter at least
| # OR
(?!^)\G # anchor: end of last match
)
\w\B # a word character followed by an other word character
\K # reset the match from match result
A way with Javascript with a callback:
var str = "This is simple SEnTeNCE with a FEW word.";
var res = str.replace(/\b(?:[a-z]*[A-Z]){2,}[a-z]*\b/g, function (m) {
return m.split('').join(' '); } );
console.log(res);
A one regex solution would be (PCRE):
(?|(?=\b(?:[a-z]*[A-Z]){2})(\w)|(?!^)\G(\w))(?!\b)
(?| # branch reset group
(?= \b (?:[a-z]* [A-Z]){2} ) # look ahead anchored at the begining of the word:
# check we are the beginning of a two-upper word
(\w) # grab the first letter
| # OR
(?!^)\G # we're following a previous match (and not
# at the beginning of the string)
(\w) # if so we're inside a wanted word, so we grab
# a character
(?!\b) # except if it's the last one (we don't want
# too many spaces)
)
And replace with
\1 # <- there's a space after the \1
See demo here.
Note that it might be easier to do it in more steps (grabbing the words, treating them individually, joining everything)...