How to insert a character every n characters from end of string





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I would like to insert a colon every five characters starting from the end of the string, preferably using regex and gsub in R.



text <- "My Very Enthusiastic Mother Just Served Us Noodles!"


I have been able to insert a colon every five characters from beginning of the text using:



gsub('(.{5})', "\1:", text, perl = T)


I have written an inelegant function for achieving this as follows:



library(dplyr)
str_reverse<-function(x){
strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "")
}

text2<-str_reverse(text)
text3<-gsub('(.{5})', "\1:", text2, perl = T)
str_reverse(text3)


to get the desired result




[1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"




Is there a way this can be achieved directly using regular expressions?










share|improve this question

























  • Consider that the stringi package has the stri_reverse function already available and super efficient.

    – nicola
    Nov 16 '18 at 12:45


















2















I would like to insert a colon every five characters starting from the end of the string, preferably using regex and gsub in R.



text <- "My Very Enthusiastic Mother Just Served Us Noodles!"


I have been able to insert a colon every five characters from beginning of the text using:



gsub('(.{5})', "\1:", text, perl = T)


I have written an inelegant function for achieving this as follows:



library(dplyr)
str_reverse<-function(x){
strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "")
}

text2<-str_reverse(text)
text3<-gsub('(.{5})', "\1:", text2, perl = T)
str_reverse(text3)


to get the desired result




[1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"




Is there a way this can be achieved directly using regular expressions?










share|improve this question

























  • Consider that the stringi package has the stri_reverse function already available and super efficient.

    – nicola
    Nov 16 '18 at 12:45














2












2








2








I would like to insert a colon every five characters starting from the end of the string, preferably using regex and gsub in R.



text <- "My Very Enthusiastic Mother Just Served Us Noodles!"


I have been able to insert a colon every five characters from beginning of the text using:



gsub('(.{5})', "\1:", text, perl = T)


I have written an inelegant function for achieving this as follows:



library(dplyr)
str_reverse<-function(x){
strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "")
}

text2<-str_reverse(text)
text3<-gsub('(.{5})', "\1:", text2, perl = T)
str_reverse(text3)


to get the desired result




[1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"




Is there a way this can be achieved directly using regular expressions?










share|improve this question
















I would like to insert a colon every five characters starting from the end of the string, preferably using regex and gsub in R.



text <- "My Very Enthusiastic Mother Just Served Us Noodles!"


I have been able to insert a colon every five characters from beginning of the text using:



gsub('(.{5})', "\1:", text, perl = T)


I have written an inelegant function for achieving this as follows:



library(dplyr)
str_reverse<-function(x){
strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "")
}

text2<-str_reverse(text)
text3<-gsub('(.{5})', "\1:", text2, perl = T)
str_reverse(text3)


to get the desired result




[1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"




Is there a way this can be achieved directly using regular expressions?







r regex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 12:29









Sotos

31.2k51741




31.2k51741










asked Nov 16 '18 at 12:14









Joseph KigothoJoseph Kigotho

226




226













  • Consider that the stringi package has the stri_reverse function already available and super efficient.

    – nicola
    Nov 16 '18 at 12:45



















  • Consider that the stringi package has the stri_reverse function already available and super efficient.

    – nicola
    Nov 16 '18 at 12:45

















Consider that the stringi package has the stri_reverse function already available and super efficient.

– nicola
Nov 16 '18 at 12:45





Consider that the stringi package has the stri_reverse function already available and super efficient.

– nicola
Nov 16 '18 at 12:45












1 Answer
1






active

oldest

votes


















4














You may use



gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"


See the regex demo



The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.



If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):



'(?s)(?=(?:.{5})+$)'





share|improve this answer



















  • 1





    @AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:46











  • thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

    – Andre Elrico
    Nov 16 '18 at 12:49











  • @AndreElrico You may want to read my quantfier explanations, too.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:53














Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337711%2fhow-to-insert-a-character-every-n-characters-from-end-of-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














You may use



gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"


See the regex demo



The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.



If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):



'(?s)(?=(?:.{5})+$)'





share|improve this answer



















  • 1





    @AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:46











  • thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

    – Andre Elrico
    Nov 16 '18 at 12:49











  • @AndreElrico You may want to read my quantfier explanations, too.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:53


















4














You may use



gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"


See the regex demo



The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.



If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):



'(?s)(?=(?:.{5})+$)'





share|improve this answer



















  • 1





    @AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:46











  • thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

    – Andre Elrico
    Nov 16 '18 at 12:49











  • @AndreElrico You may want to read my quantfier explanations, too.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:53
















4












4








4







You may use



gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"


See the regex demo



The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.



If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):



'(?s)(?=(?:.{5})+$)'





share|improve this answer













You may use



gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"


See the regex demo



The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.



If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):



'(?s)(?=(?:.{5})+$)'






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 12:17









Wiktor StribiżewWiktor Stribiżew

329k16149228




329k16149228








  • 1





    @AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:46











  • thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

    – Andre Elrico
    Nov 16 '18 at 12:49











  • @AndreElrico You may want to read my quantfier explanations, too.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:53
















  • 1





    @AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:46











  • thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

    – Andre Elrico
    Nov 16 '18 at 12:49











  • @AndreElrico You may want to read my quantfier explanations, too.

    – Wiktor Stribiżew
    Nov 16 '18 at 12:53










1




1





@AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

– Wiktor Stribiżew
Nov 16 '18 at 12:46





@AndreElrico 1) It does not matter if you use lazy or greedy quantifiers here, (?=(?:.{5})+?$) = (?=(?:.{5})+$) because the next pattern is $, end of string and .{5} goes matching up to the end of the string anyway, 2) since the regex searches for matches from left to right, the 2nd position is matched, not the 5 from the end. PCRE regex cannot be set to search from the end.

– Wiktor Stribiżew
Nov 16 '18 at 12:46













thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

– Andre Elrico
Nov 16 '18 at 12:49





thanks you also found this here rexegg.com/regex-quantifiers.html#longest_shortest . this was a missing piece in my brain

– Andre Elrico
Nov 16 '18 at 12:49













@AndreElrico You may want to read my quantfier explanations, too.

– Wiktor Stribiżew
Nov 16 '18 at 12:53







@AndreElrico You may want to read my quantfier explanations, too.

– Wiktor Stribiżew
Nov 16 '18 at 12:53






















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337711%2fhow-to-insert-a-character-every-n-characters-from-end-of-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Danny Elfman

Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues