Add number in the string after each letterWhat is the difference between String and string in C#?How to...

Is it common to refer to someone as "Prof. Dr. [LastName]"?

How to ask a Ranger to use Favored Enemy without spoiling the story for the player?

SQL Server 2017 crashes when backing up because filepath is wrong

Is layered encryption more secure than long passwords?

Can a planet be tidally unlocked?

bash aliases do not expand even with shopt expand_aliases

Have the UK Conservatives lost the working majority and if so, what does this mean?

How can I make my enemies feel real and make combat more engaging?

Isn't a semicolon (';') needed after a function declaration in C++?

Are all power cords made equal?

Why can all solutions to the simple harmonic motion equation be written in terms of sines and cosines?

How do I avoid the "chosen hero" feeling?

Is there any danger of my neighbor having my wife's signature?

Are there any rules for handling distractions whilst performing skill checks?

Buying a "Used" Router

Can I do anything else with aspersions other than cast them?

Is it Safe to Plug an Extension Cord Into a Power Strip?

Coworker asking me to not bring cakes due to self control issue. What should I do?

I am a loser when it comes to jobs, what possibilities do I have?

When distributing a Linux kernel driver as source code, what's the difference between Proprietary and GPL license?

Why does this quiz question say that protons and electrons do not combine to form neutrons?

How can I persuade an unwilling soul to become willing?

What legally stops the UK from having another referendum on Brexit

Short story about a man betting a group he could tell a story, and one of them would disappear and the others would not notice



Add number in the string after each letter


What is the difference between String and string in C#?How to validate an email address using a regular expression?How do I read / convert an InputStream into a String in Java?Case insensitive 'Contains(string)'Convert bytes to a string?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?Why is char[] preferred over String for passwords?













7















I have several strings with a fixed format.



The format is one letter followed by a number, e.g., A3B1C7D1.



However, if the number behind a letter is 1, the string is written as A3BC7D.



What I want to do is to insert number 1, and convert the string from A3BC7D to A3B1C7D1.



My example data is



strings <- c("A", "A3BC3", "A2B1C")


What I want to get is:



strings_new <- c("A1", "A3B1C3", "A2B1C1")


Thanks a lot!










share|improve this question





























    7















    I have several strings with a fixed format.



    The format is one letter followed by a number, e.g., A3B1C7D1.



    However, if the number behind a letter is 1, the string is written as A3BC7D.



    What I want to do is to insert number 1, and convert the string from A3BC7D to A3B1C7D1.



    My example data is



    strings <- c("A", "A3BC3", "A2B1C")


    What I want to get is:



    strings_new <- c("A1", "A3B1C3", "A2B1C1")


    Thanks a lot!










    share|improve this question



























      7












      7








      7


      1






      I have several strings with a fixed format.



      The format is one letter followed by a number, e.g., A3B1C7D1.



      However, if the number behind a letter is 1, the string is written as A3BC7D.



      What I want to do is to insert number 1, and convert the string from A3BC7D to A3B1C7D1.



      My example data is



      strings <- c("A", "A3BC3", "A2B1C")


      What I want to get is:



      strings_new <- c("A1", "A3B1C3", "A2B1C1")


      Thanks a lot!










      share|improve this question
















      I have several strings with a fixed format.



      The format is one letter followed by a number, e.g., A3B1C7D1.



      However, if the number behind a letter is 1, the string is written as A3BC7D.



      What I want to do is to insert number 1, and convert the string from A3BC7D to A3B1C7D1.



      My example data is



      strings <- c("A", "A3BC3", "A2B1C")


      What I want to get is:



      strings_new <- c("A1", "A3B1C3", "A2B1C1")


      Thanks a lot!







      r regex string






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      markus

      13.1k1234




      13.1k1234










      asked 2 hours ago









      DongDong

      1466




      1466
























          4 Answers
          4






          active

          oldest

          votes


















          3














          Another option:



          gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\1\21", strings, perl = T)


          Output:



          [1] "A1"     "A3B1C3" "A2B1C1"


          Or if you only have capitals, just:



          gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\1\21", strings, perl = T)


          Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.






          share|improve this answer

































            7














            IIUC you could do:



            gsub("(\D)(\D|$)", "\11\2", strings)
            #[1] "A1" "A3B1C3" "A2B1C1"




            We create two capture groups, the first is a signle non-digit (\D), the second is either a single non-digit or the end of the string (\D|$). Whenever there's a match in a string, this means two letters (non-digits) follow each other without a number in between. Hence, we use the replacement \11\2 to replace it with group1, then a 1, then group2 (which can also be the end of the string).






            share|improve this answer


























            • If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

              – Dong
              2 mins ago



















            1














            Find all (uppercase) letters ([A-Z]) that is not followed by a number and replace it with that string + 1:



            gsub("([A-Z])(?![0-9])", "\11", strings, perl = TRUE)
            # [1] "A1" "A3B1C3" "A2B1C1"





            share|improve this answer

































              0














              strings[!grepl("[0-9]$",strings)]=paste0(strings[!grepl("[0-9]$",strings)],"1")
              [1] "A1" "A3BC3" "A2B1C1"


              We first grep all positions that do not end with a number, and paste a 1 to them.






              share|improve this answer



















              • 9





                Almost. Check the second element it should be "A3B1C3"

                – markus
                2 hours ago













              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%2f54825764%2fadd-number-in-the-string-after-each-letter%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              Another option:



              gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\1\21", strings, perl = T)


              Output:



              [1] "A1"     "A3B1C3" "A2B1C1"


              Or if you only have capitals, just:



              gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\1\21", strings, perl = T)


              Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.






              share|improve this answer






























                3














                Another option:



                gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\1\21", strings, perl = T)


                Output:



                [1] "A1"     "A3B1C3" "A2B1C1"


                Or if you only have capitals, just:



                gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\1\21", strings, perl = T)


                Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.






                share|improve this answer




























                  3












                  3








                  3







                  Another option:



                  gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\1\21", strings, perl = T)


                  Output:



                  [1] "A1"     "A3B1C3" "A2B1C1"


                  Or if you only have capitals, just:



                  gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\1\21", strings, perl = T)


                  Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.






                  share|improve this answer















                  Another option:



                  gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "\1\21", strings, perl = T)


                  Output:



                  [1] "A1"     "A3B1C3" "A2B1C1"


                  Or if you only have capitals, just:



                  gsub("([A-Z])(?=[A-Z])|([A-Z])$", "\1\21", strings, perl = T)


                  Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 2 hours ago

























                  answered 2 hours ago









                  arg0nautarg0naut

                  4,1191315




                  4,1191315

























                      7














                      IIUC you could do:



                      gsub("(\D)(\D|$)", "\11\2", strings)
                      #[1] "A1" "A3B1C3" "A2B1C1"




                      We create two capture groups, the first is a signle non-digit (\D), the second is either a single non-digit or the end of the string (\D|$). Whenever there's a match in a string, this means two letters (non-digits) follow each other without a number in between. Hence, we use the replacement \11\2 to replace it with group1, then a 1, then group2 (which can also be the end of the string).






                      share|improve this answer


























                      • If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                        – Dong
                        2 mins ago
















                      7














                      IIUC you could do:



                      gsub("(\D)(\D|$)", "\11\2", strings)
                      #[1] "A1" "A3B1C3" "A2B1C1"




                      We create two capture groups, the first is a signle non-digit (\D), the second is either a single non-digit or the end of the string (\D|$). Whenever there's a match in a string, this means two letters (non-digits) follow each other without a number in between. Hence, we use the replacement \11\2 to replace it with group1, then a 1, then group2 (which can also be the end of the string).






                      share|improve this answer


























                      • If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                        – Dong
                        2 mins ago














                      7












                      7








                      7







                      IIUC you could do:



                      gsub("(\D)(\D|$)", "\11\2", strings)
                      #[1] "A1" "A3B1C3" "A2B1C1"




                      We create two capture groups, the first is a signle non-digit (\D), the second is either a single non-digit or the end of the string (\D|$). Whenever there's a match in a string, this means two letters (non-digits) follow each other without a number in between. Hence, we use the replacement \11\2 to replace it with group1, then a 1, then group2 (which can also be the end of the string).






                      share|improve this answer















                      IIUC you could do:



                      gsub("(\D)(\D|$)", "\11\2", strings)
                      #[1] "A1" "A3B1C3" "A2B1C1"




                      We create two capture groups, the first is a signle non-digit (\D), the second is either a single non-digit or the end of the string (\D|$). Whenever there's a match in a string, this means two letters (non-digits) follow each other without a number in between. Hence, we use the replacement \11\2 to replace it with group1, then a 1, then group2 (which can also be the end of the string).







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 2 hours ago

























                      answered 2 hours ago









                      docendo discimusdocendo discimus

                      51.9k1179117




                      51.9k1179117













                      • If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                        – Dong
                        2 mins ago



















                      • If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                        – Dong
                        2 mins ago

















                      If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                      – Dong
                      2 mins ago





                      If I run gsub("(\D)(\D|$)", "\11\2", "AB"), I got A1B

                      – Dong
                      2 mins ago











                      1














                      Find all (uppercase) letters ([A-Z]) that is not followed by a number and replace it with that string + 1:



                      gsub("([A-Z])(?![0-9])", "\11", strings, perl = TRUE)
                      # [1] "A1" "A3B1C3" "A2B1C1"





                      share|improve this answer






























                        1














                        Find all (uppercase) letters ([A-Z]) that is not followed by a number and replace it with that string + 1:



                        gsub("([A-Z])(?![0-9])", "\11", strings, perl = TRUE)
                        # [1] "A1" "A3B1C3" "A2B1C1"





                        share|improve this answer




























                          1












                          1








                          1







                          Find all (uppercase) letters ([A-Z]) that is not followed by a number and replace it with that string + 1:



                          gsub("([A-Z])(?![0-9])", "\11", strings, perl = TRUE)
                          # [1] "A1" "A3B1C3" "A2B1C1"





                          share|improve this answer















                          Find all (uppercase) letters ([A-Z]) that is not followed by a number and replace it with that string + 1:



                          gsub("([A-Z])(?![0-9])", "\11", strings, perl = TRUE)
                          # [1] "A1" "A3B1C3" "A2B1C1"






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 4 mins ago

























                          answered 29 mins ago









                          sindri_baldursindri_baldur

                          7,7941032




                          7,7941032























                              0














                              strings[!grepl("[0-9]$",strings)]=paste0(strings[!grepl("[0-9]$",strings)],"1")
                              [1] "A1" "A3BC3" "A2B1C1"


                              We first grep all positions that do not end with a number, and paste a 1 to them.






                              share|improve this answer



















                              • 9





                                Almost. Check the second element it should be "A3B1C3"

                                – markus
                                2 hours ago


















                              0














                              strings[!grepl("[0-9]$",strings)]=paste0(strings[!grepl("[0-9]$",strings)],"1")
                              [1] "A1" "A3BC3" "A2B1C1"


                              We first grep all positions that do not end with a number, and paste a 1 to them.






                              share|improve this answer



















                              • 9





                                Almost. Check the second element it should be "A3B1C3"

                                – markus
                                2 hours ago
















                              0












                              0








                              0







                              strings[!grepl("[0-9]$",strings)]=paste0(strings[!grepl("[0-9]$",strings)],"1")
                              [1] "A1" "A3BC3" "A2B1C1"


                              We first grep all positions that do not end with a number, and paste a 1 to them.






                              share|improve this answer













                              strings[!grepl("[0-9]$",strings)]=paste0(strings[!grepl("[0-9]$",strings)],"1")
                              [1] "A1" "A3BC3" "A2B1C1"


                              We first grep all positions that do not end with a number, and paste a 1 to them.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 2 hours ago









                              boskiboski

                              490210




                              490210








                              • 9





                                Almost. Check the second element it should be "A3B1C3"

                                – markus
                                2 hours ago
















                              • 9





                                Almost. Check the second element it should be "A3B1C3"

                                – markus
                                2 hours ago










                              9




                              9





                              Almost. Check the second element it should be "A3B1C3"

                              – markus
                              2 hours ago







                              Almost. Check the second element it should be "A3B1C3"

                              – markus
                              2 hours ago




















                              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%2f54825764%2fadd-number-in-the-string-after-each-letter%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

                              Щит и меч (фильм) Содержание Названия серий | Сюжет |...

                              Венесуэла на летних Олимпийских играх 2000 Содержание Состав...

                              Meter-Bus Содержание Параметры шины | Стандартизация |...