What's the idiomatic (or best) way to trim surrounding whitespace from a string?Using the count of coincidence from a regexp as replacement text?Regexp \textvars(([:ascii:]+)) -> |1| doesn't workHow to make a dot match a newlinequery replace ingonring new linesmodify tab length for eclim-java-formatAuto-indenting C code with tabs for blocks and spaces for other wrapping?Passing a string with substitutions to the “perform-replace” commandWhat is the best way to search forward/backward for a token?How to define abbrev boundaries and where to put them?Whitespace and newlines in regexps?

What verb goes with "coup"?

What could a Medieval society do with excess animal blood?

Why do movie directors use brown tint on Mexico cities?

Does an NPC know when a character has passed the save for Truth Serum?

Which high-degree derivatives play an essential role?

Disk usage confusion: 10G missing on Linux home partition on SSD

What is my external HDD doing?

Odd PCB Layout for Voltage Regulator

Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?

How useful would a hydroelectric power plant be in the post-apocalypse world?

Processes in a session in an interactive shell vs in a script

Why did the Apple IIe make a hideous noise if you inserted the disk upside down?

Why would Dementors torture a Death Eater if they are loyal to Voldemort?

How far can gerrymandering go?

Why am I getting an electric shock from the water in my hot tub?

How does the 'five minute adventuring day' affect class balance?

How can this fractal shape perfectly cover a certain platonic solid?

Basic calculations in PGF/TikZ for loop

"in 60 seconds or less" or "in 60 seconds or fewer"?

Is it OK to throw pebbles and stones in streams, waterfalls, ponds, etc.?

English idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)

Why was Pan Am Flight 103 flying over Lockerbie?

Does "boire un jus" tend to mean "coffee" or "juice of fruit"?

iMac 2019: Can I mix the old modules with the new ones when upgrading RAM?



What's the idiomatic (or best) way to trim surrounding whitespace from a string?


Using the count of coincidence from a regexp as replacement text?Regexp \textvars(([:ascii:]+)) -> |1| doesn't workHow to make a dot match a newlinequery replace ingonring new linesmodify tab length for eclim-java-formatAuto-indenting C code with tabs for blocks and spaces for other wrapping?Passing a string with substitutions to the “perform-replace” commandWhat is the best way to search forward/backward for a token?How to define abbrev boundaries and where to put them?Whitespace and newlines in regexps?













3















I'm working with strings which may have any number of prefix and suffix spaces, tabs, newlines, etc. Currently I have this:



(replace-regexp-in-string
"^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
"\1" my-string)









share|improve this question









New contributor



user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.























    3















    I'm working with strings which may have any number of prefix and suffix spaces, tabs, newlines, etc. Currently I have this:



    (replace-regexp-in-string
    "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
    "\1" my-string)









    share|improve this question









    New contributor



    user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















      3












      3








      3








      I'm working with strings which may have any number of prefix and suffix spaces, tabs, newlines, etc. Currently I have this:



      (replace-regexp-in-string
      "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
      "\1" my-string)









      share|improve this question









      New contributor



      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I'm working with strings which may have any number of prefix and suffix spaces, tabs, newlines, etc. Currently I have this:



      (replace-regexp-in-string
      "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
      "\1" my-string)






      regular-expressions whitespace string






      share|improve this question









      New contributor



      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question









      New contributor



      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question








      edited 5 hours ago









      Drew

      49.9k4 gold badges65 silver badges112 bronze badges




      49.9k4 gold badges65 silver badges112 bronze badges






      New contributor



      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked 8 hours ago









      user23847user23847

      161 bronze badge




      161 bronze badge




      New contributor



      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      user23847 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          2 Answers
          2






          active

          oldest

          votes


















          3














          There is the string manipulation library s.el where trimming whitespace and newlines at the beginning and the end of a string is implemented as function s-trim. I cite that function here with its dependencies:



          (defun s-trim-left (s)
          "Remove whitespace at the beginning of S."
          (declare (pure t) (side-effect-free t))
          (save-match-data
          (if (string-match "\`[ tnr]+" s)
          (replace-match "" t t s)
          s)))

          (defun s-trim-right (s)
          "Remove whitespace at the end of S."
          (save-match-data
          (declare (pure t) (side-effect-free t))
          (if (string-match "[ tnr]+\'" s)
          (replace-match "" t t s)
          s)))

          (defun s-trim (s)
          "Remove whitespace at the beginning and end of S."
          (declare (pure t) (side-effect-free t))
          (s-trim-left (s-trim-right s)))


          Some differences to your first attempt



          (replace-regexp-in-string
          "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
          "\1" my-string)


          are noteworthy:




          1. ^ as first char does not match the beginning of the string but the beginning of a line in the string. Similarly, $ matches not the end of the string but the end of a line. Use ` for the beginning of the string and ' for the end.

          2. Do not match stuff which you actually do not need to analyze. This regards the stuff \(.*\) which you match as the actual string to be returned. It may be long and you force replace-regexp-in-string to scan it.

          3. The character class [:alnum:] does not include characters of syntax class symbol. Therefore your function would also trim away characters that belong to this character class.





          share|improve this answer

























          • Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

            – user23847
            6 hours ago












          • @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

            – Tobias
            6 hours ago


















          1















          What's the idiomatic (or best) way to trim surrounding whitespace from a string?




          The built-in library subr-x.el has included the inline functions string-trim-left, string-trim-right, and string-trim since Emacs 24.4:



          (eval-when-compile (require 'subr-x))

          (string-trim "nrstfoonrst") ; => "foo"


          Since Emacs 26.1 these inline functions also accept optional regexp arguments:



          (eval-when-compile (require 'subr-x))

          (string-trim "aabbcc" "a+" "c+") ; => "bb"





          share|improve this answer

























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "583"
            ;
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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
            );



            );






            user23847 is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2femacs.stackexchange.com%2fquestions%2f51311%2fwhats-the-idiomatic-or-best-way-to-trim-surrounding-whitespace-from-a-string%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            There is the string manipulation library s.el where trimming whitespace and newlines at the beginning and the end of a string is implemented as function s-trim. I cite that function here with its dependencies:



            (defun s-trim-left (s)
            "Remove whitespace at the beginning of S."
            (declare (pure t) (side-effect-free t))
            (save-match-data
            (if (string-match "\`[ tnr]+" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim-right (s)
            "Remove whitespace at the end of S."
            (save-match-data
            (declare (pure t) (side-effect-free t))
            (if (string-match "[ tnr]+\'" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim (s)
            "Remove whitespace at the beginning and end of S."
            (declare (pure t) (side-effect-free t))
            (s-trim-left (s-trim-right s)))


            Some differences to your first attempt



            (replace-regexp-in-string
            "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
            "\1" my-string)


            are noteworthy:




            1. ^ as first char does not match the beginning of the string but the beginning of a line in the string. Similarly, $ matches not the end of the string but the end of a line. Use ` for the beginning of the string and ' for the end.

            2. Do not match stuff which you actually do not need to analyze. This regards the stuff \(.*\) which you match as the actual string to be returned. It may be long and you force replace-regexp-in-string to scan it.

            3. The character class [:alnum:] does not include characters of syntax class symbol. Therefore your function would also trim away characters that belong to this character class.





            share|improve this answer

























            • Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

              – user23847
              6 hours ago












            • @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

              – Tobias
              6 hours ago















            3














            There is the string manipulation library s.el where trimming whitespace and newlines at the beginning and the end of a string is implemented as function s-trim. I cite that function here with its dependencies:



            (defun s-trim-left (s)
            "Remove whitespace at the beginning of S."
            (declare (pure t) (side-effect-free t))
            (save-match-data
            (if (string-match "\`[ tnr]+" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim-right (s)
            "Remove whitespace at the end of S."
            (save-match-data
            (declare (pure t) (side-effect-free t))
            (if (string-match "[ tnr]+\'" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim (s)
            "Remove whitespace at the beginning and end of S."
            (declare (pure t) (side-effect-free t))
            (s-trim-left (s-trim-right s)))


            Some differences to your first attempt



            (replace-regexp-in-string
            "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
            "\1" my-string)


            are noteworthy:




            1. ^ as first char does not match the beginning of the string but the beginning of a line in the string. Similarly, $ matches not the end of the string but the end of a line. Use ` for the beginning of the string and ' for the end.

            2. Do not match stuff which you actually do not need to analyze. This regards the stuff \(.*\) which you match as the actual string to be returned. It may be long and you force replace-regexp-in-string to scan it.

            3. The character class [:alnum:] does not include characters of syntax class symbol. Therefore your function would also trim away characters that belong to this character class.





            share|improve this answer

























            • Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

              – user23847
              6 hours ago












            • @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

              – Tobias
              6 hours ago













            3












            3








            3







            There is the string manipulation library s.el where trimming whitespace and newlines at the beginning and the end of a string is implemented as function s-trim. I cite that function here with its dependencies:



            (defun s-trim-left (s)
            "Remove whitespace at the beginning of S."
            (declare (pure t) (side-effect-free t))
            (save-match-data
            (if (string-match "\`[ tnr]+" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim-right (s)
            "Remove whitespace at the end of S."
            (save-match-data
            (declare (pure t) (side-effect-free t))
            (if (string-match "[ tnr]+\'" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim (s)
            "Remove whitespace at the beginning and end of S."
            (declare (pure t) (side-effect-free t))
            (s-trim-left (s-trim-right s)))


            Some differences to your first attempt



            (replace-regexp-in-string
            "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
            "\1" my-string)


            are noteworthy:




            1. ^ as first char does not match the beginning of the string but the beginning of a line in the string. Similarly, $ matches not the end of the string but the end of a line. Use ` for the beginning of the string and ' for the end.

            2. Do not match stuff which you actually do not need to analyze. This regards the stuff \(.*\) which you match as the actual string to be returned. It may be long and you force replace-regexp-in-string to scan it.

            3. The character class [:alnum:] does not include characters of syntax class symbol. Therefore your function would also trim away characters that belong to this character class.





            share|improve this answer















            There is the string manipulation library s.el where trimming whitespace and newlines at the beginning and the end of a string is implemented as function s-trim. I cite that function here with its dependencies:



            (defun s-trim-left (s)
            "Remove whitespace at the beginning of S."
            (declare (pure t) (side-effect-free t))
            (save-match-data
            (if (string-match "\`[ tnr]+" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim-right (s)
            "Remove whitespace at the end of S."
            (save-match-data
            (declare (pure t) (side-effect-free t))
            (if (string-match "[ tnr]+\'" s)
            (replace-match "" t t s)
            s)))

            (defun s-trim (s)
            "Remove whitespace at the beginning and end of S."
            (declare (pure t) (side-effect-free t))
            (s-trim-left (s-trim-right s)))


            Some differences to your first attempt



            (replace-regexp-in-string
            "^[^[:alnum:]]*\(.*\)[^[:alnum:]]*$"
            "\1" my-string)


            are noteworthy:




            1. ^ as first char does not match the beginning of the string but the beginning of a line in the string. Similarly, $ matches not the end of the string but the end of a line. Use ` for the beginning of the string and ' for the end.

            2. Do not match stuff which you actually do not need to analyze. This regards the stuff \(.*\) which you match as the actual string to be returned. It may be long and you force replace-regexp-in-string to scan it.

            3. The character class [:alnum:] does not include characters of syntax class symbol. Therefore your function would also trim away characters that belong to this character class.






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 5 hours ago









            NickD

            3,0241 gold badge6 silver badges17 bronze badges




            3,0241 gold badge6 silver badges17 bronze badges










            answered 6 hours ago









            TobiasTobias

            17.1k1 gold badge11 silver badges39 bronze badges




            17.1k1 gold badge11 silver badges39 bronze badges












            • Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

              – user23847
              6 hours ago












            • @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

              – Tobias
              6 hours ago

















            • Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

              – user23847
              6 hours ago












            • @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

              – Tobias
              6 hours ago
















            Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

            – user23847
            6 hours ago






            Thanks for s.el! As to your three points: 1. I thought the escaped backquote and escaped apostrophe were for buffers. 2. Good point! 3. I'm not worried about non-alnum characters in this case, but in other cases I might be.

            – user23847
            6 hours ago














            @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

            – Tobias
            6 hours ago





            @user23847 About 1.: The manual uses the phrase "string or buffer". I cite: ` matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against. ' matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

            – Tobias
            6 hours ago











            1















            What's the idiomatic (or best) way to trim surrounding whitespace from a string?




            The built-in library subr-x.el has included the inline functions string-trim-left, string-trim-right, and string-trim since Emacs 24.4:



            (eval-when-compile (require 'subr-x))

            (string-trim "nrstfoonrst") ; => "foo"


            Since Emacs 26.1 these inline functions also accept optional regexp arguments:



            (eval-when-compile (require 'subr-x))

            (string-trim "aabbcc" "a+" "c+") ; => "bb"





            share|improve this answer



























              1















              What's the idiomatic (or best) way to trim surrounding whitespace from a string?




              The built-in library subr-x.el has included the inline functions string-trim-left, string-trim-right, and string-trim since Emacs 24.4:



              (eval-when-compile (require 'subr-x))

              (string-trim "nrstfoonrst") ; => "foo"


              Since Emacs 26.1 these inline functions also accept optional regexp arguments:



              (eval-when-compile (require 'subr-x))

              (string-trim "aabbcc" "a+" "c+") ; => "bb"





              share|improve this answer

























                1












                1








                1








                What's the idiomatic (or best) way to trim surrounding whitespace from a string?




                The built-in library subr-x.el has included the inline functions string-trim-left, string-trim-right, and string-trim since Emacs 24.4:



                (eval-when-compile (require 'subr-x))

                (string-trim "nrstfoonrst") ; => "foo"


                Since Emacs 26.1 these inline functions also accept optional regexp arguments:



                (eval-when-compile (require 'subr-x))

                (string-trim "aabbcc" "a+" "c+") ; => "bb"





                share|improve this answer














                What's the idiomatic (or best) way to trim surrounding whitespace from a string?




                The built-in library subr-x.el has included the inline functions string-trim-left, string-trim-right, and string-trim since Emacs 24.4:



                (eval-when-compile (require 'subr-x))

                (string-trim "nrstfoonrst") ; => "foo"


                Since Emacs 26.1 these inline functions also accept optional regexp arguments:



                (eval-when-compile (require 'subr-x))

                (string-trim "aabbcc" "a+" "c+") ; => "bb"






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 hours ago









                BasilBasil

                5,9069 silver badges36 bronze badges




                5,9069 silver badges36 bronze badges




















                    user23847 is a new contributor. Be nice, and check out our Code of Conduct.









                    draft saved

                    draft discarded


















                    user23847 is a new contributor. Be nice, and check out our Code of Conduct.












                    user23847 is a new contributor. Be nice, and check out our Code of Conduct.











                    user23847 is a new contributor. Be nice, and check out our Code of Conduct.














                    Thanks for contributing an answer to Emacs Stack Exchange!


                    • 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%2femacs.stackexchange.com%2fquestions%2f51311%2fwhats-the-idiomatic-or-best-way-to-trim-surrounding-whitespace-from-a-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

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її