Regular Expressions: Search in list












44















I want to filter strings in a list based on a regular expression.



Is there something better than [x for x in list if r.match(x)] ?










share|improve this question





























    44















    I want to filter strings in a list based on a regular expression.



    Is there something better than [x for x in list if r.match(x)] ?










    share|improve this question



























      44












      44








      44


      18






      I want to filter strings in a list based on a regular expression.



      Is there something better than [x for x in list if r.match(x)] ?










      share|improve this question
















      I want to filter strings in a list based on a regular expression.



      Is there something better than [x for x in list if r.match(x)] ?







      python regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 6 '14 at 19:46









      RockPaperLizard

      2,13252236




      2,13252236










      asked Sep 4 '10 at 0:13









      leolukleoluk

      9,00843445




      9,00843445
























          3 Answers
          3






          active

          oldest

          votes


















          79














          You can create an iterator in Python 3.x or a list in Python 2.x by using:



          filter(r.match, list)


          To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).






          share|improve this answer


























          • Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

            – Ivo van der Wijk
            Sep 4 '10 at 0:41






          • 27





            @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

            – sepp2k
            Sep 4 '10 at 0:47











          • what is r.match here?

            – rbatt
            Oct 12 '18 at 11:48











          • @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

            – sepp2k
            Oct 12 '18 at 21:33



















          71














          Full Example (Python 3):
          For Python 2.x look into Note below



          import re

          mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          r = re.compile(".*cat")
          newlist = list(filter(r.match, mylist)) # Read Note
          print(newlist)


          Prints:



          ['cat', 'wildcat', 'thundercat']




          Note:



          For Python 2.x users, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).



          Python 3 code example
          Python 2.x code example






          share|improve this answer





















          • 4





            Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

            – Joshua
            Oct 13 '16 at 11:08






          • 1





            According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

            – Mercury
            Oct 13 '16 at 13:24








          • 1





            Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

            – Joshua
            Oct 14 '16 at 12:25






          • 4





            @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

            – James Draper
            Jan 10 '17 at 18:42













          • @James Draper Thank you James. It was a good reminder.

            – Joshua
            Jan 10 '17 at 18:48



















          3














          Just in case someone comes here in future, there is another pythonic way to do it. First you need to create the regex and then then filter



          import re

          inilist =["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          regex = re.compile(r'.*cat')
          selectobj = filter(regex.search, inilist)
          selectobj


          results:



          ['cat', 'wildcat', 'thundercat']





          share|improve this answer
























          • That's literally what the accepted answer suggests

            – leoluk
            Nov 14 '18 at 12:31











          • @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

            – enter_display_name_here
            Jan 15 at 15:42











          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%2f3640359%2fregular-expressions-search-in-list%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          79














          You can create an iterator in Python 3.x or a list in Python 2.x by using:



          filter(r.match, list)


          To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).






          share|improve this answer


























          • Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

            – Ivo van der Wijk
            Sep 4 '10 at 0:41






          • 27





            @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

            – sepp2k
            Sep 4 '10 at 0:47











          • what is r.match here?

            – rbatt
            Oct 12 '18 at 11:48











          • @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

            – sepp2k
            Oct 12 '18 at 21:33
















          79














          You can create an iterator in Python 3.x or a list in Python 2.x by using:



          filter(r.match, list)


          To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).






          share|improve this answer


























          • Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

            – Ivo van der Wijk
            Sep 4 '10 at 0:41






          • 27





            @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

            – sepp2k
            Sep 4 '10 at 0:47











          • what is r.match here?

            – rbatt
            Oct 12 '18 at 11:48











          • @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

            – sepp2k
            Oct 12 '18 at 21:33














          79












          79








          79







          You can create an iterator in Python 3.x or a list in Python 2.x by using:



          filter(r.match, list)


          To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).






          share|improve this answer















          You can create an iterator in Python 3.x or a list in Python 2.x by using:



          filter(r.match, list)


          To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 4 '18 at 6:29









          Ev. Kounis

          10.8k21546




          10.8k21546










          answered Sep 4 '10 at 0:17









          sepp2ksepp2k

          294k38595610




          294k38595610













          • Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

            – Ivo van der Wijk
            Sep 4 '10 at 0:41






          • 27





            @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

            – sepp2k
            Sep 4 '10 at 0:47











          • what is r.match here?

            – rbatt
            Oct 12 '18 at 11:48











          • @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

            – sepp2k
            Oct 12 '18 at 21:33



















          • Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

            – Ivo van der Wijk
            Sep 4 '10 at 0:41






          • 27





            @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

            – sepp2k
            Sep 4 '10 at 0:47











          • what is r.match here?

            – rbatt
            Oct 12 '18 at 11:48











          • @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

            – sepp2k
            Oct 12 '18 at 21:33

















          Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

          – Ivo van der Wijk
          Sep 4 '10 at 0:41





          Actually, list comprehensions are usually prefered over functional constructs such as filter, reduce, lambda, etc.

          – Ivo van der Wijk
          Sep 4 '10 at 0:41




          27




          27





          @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

          – sepp2k
          Sep 4 '10 at 0:47





          @Ivo: They are usually preferred because they're usually clearer and often more succinct. However in this case, the filter version is perfectly clear and has much less noise.

          – sepp2k
          Sep 4 '10 at 0:47













          what is r.match here?

          – rbatt
          Oct 12 '18 at 11:48





          what is r.match here?

          – rbatt
          Oct 12 '18 at 11:48













          @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

          – sepp2k
          Oct 12 '18 at 21:33





          @rbatt r.match is a method that, when applied to a given string, finds whether the regex r matches that string (and returns a corresponding match object if so, but that doesn't matter in this case as we just care whether the result is truthy)

          – sepp2k
          Oct 12 '18 at 21:33













          71














          Full Example (Python 3):
          For Python 2.x look into Note below



          import re

          mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          r = re.compile(".*cat")
          newlist = list(filter(r.match, mylist)) # Read Note
          print(newlist)


          Prints:



          ['cat', 'wildcat', 'thundercat']




          Note:



          For Python 2.x users, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).



          Python 3 code example
          Python 2.x code example






          share|improve this answer





















          • 4





            Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

            – Joshua
            Oct 13 '16 at 11:08






          • 1





            According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

            – Mercury
            Oct 13 '16 at 13:24








          • 1





            Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

            – Joshua
            Oct 14 '16 at 12:25






          • 4





            @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

            – James Draper
            Jan 10 '17 at 18:42













          • @James Draper Thank you James. It was a good reminder.

            – Joshua
            Jan 10 '17 at 18:48
















          71














          Full Example (Python 3):
          For Python 2.x look into Note below



          import re

          mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          r = re.compile(".*cat")
          newlist = list(filter(r.match, mylist)) # Read Note
          print(newlist)


          Prints:



          ['cat', 'wildcat', 'thundercat']




          Note:



          For Python 2.x users, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).



          Python 3 code example
          Python 2.x code example






          share|improve this answer





















          • 4





            Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

            – Joshua
            Oct 13 '16 at 11:08






          • 1





            According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

            – Mercury
            Oct 13 '16 at 13:24








          • 1





            Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

            – Joshua
            Oct 14 '16 at 12:25






          • 4





            @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

            – James Draper
            Jan 10 '17 at 18:42













          • @James Draper Thank you James. It was a good reminder.

            – Joshua
            Jan 10 '17 at 18:48














          71












          71








          71







          Full Example (Python 3):
          For Python 2.x look into Note below



          import re

          mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          r = re.compile(".*cat")
          newlist = list(filter(r.match, mylist)) # Read Note
          print(newlist)


          Prints:



          ['cat', 'wildcat', 'thundercat']




          Note:



          For Python 2.x users, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).



          Python 3 code example
          Python 2.x code example






          share|improve this answer















          Full Example (Python 3):
          For Python 2.x look into Note below



          import re

          mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          r = re.compile(".*cat")
          newlist = list(filter(r.match, mylist)) # Read Note
          print(newlist)


          Prints:



          ['cat', 'wildcat', 'thundercat']




          Note:



          For Python 2.x users, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).



          Python 3 code example
          Python 2.x code example







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 14 '18 at 7:00

























          answered Sep 20 '16 at 11:41









          MercuryMercury

          2,6832027




          2,6832027








          • 4





            Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

            – Joshua
            Oct 13 '16 at 11:08






          • 1





            According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

            – Mercury
            Oct 13 '16 at 13:24








          • 1





            Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

            – Joshua
            Oct 14 '16 at 12:25






          • 4





            @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

            – James Draper
            Jan 10 '17 at 18:42













          • @James Draper Thank you James. It was a good reminder.

            – Joshua
            Jan 10 '17 at 18:48














          • 4





            Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

            – Joshua
            Oct 13 '16 at 11:08






          • 1





            According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

            – Mercury
            Oct 13 '16 at 13:24








          • 1





            Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

            – Joshua
            Oct 14 '16 at 12:25






          • 4





            @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

            – James Draper
            Jan 10 '17 at 18:42













          • @James Draper Thank you James. It was a good reminder.

            – Joshua
            Jan 10 '17 at 18:48








          4




          4





          Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

          – Joshua
          Oct 13 '16 at 11:08





          Hi there, When I run the above code, I get <filter object at 0x1057acda0> What am I doing wrong?

          – Joshua
          Oct 13 '16 at 11:08




          1




          1





          According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

          – Mercury
          Oct 13 '16 at 13:24







          According to python docs (python 2.7.12): docs.python.org/2/library/functions.html#filter filter returns a list not an object. You can also check that code: repl.it/X3G/5786 (just hit run)

          – Mercury
          Oct 13 '16 at 13:24






          1




          1





          Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

          – Joshua
          Oct 14 '16 at 12:25





          Thank you. I am using Python 3.5.2 on a Mac. I tried your link. Of course it works, though not sure why I get that msg. I even removed the str since filter returns a list anyway, to no avail...

          – Joshua
          Oct 14 '16 at 12:25




          4




          4





          @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

          – James Draper
          Jan 10 '17 at 18:42







          @joshua you've probably figured this out by now but try print(list(newlist)) or print([i for i in newlist])

          – James Draper
          Jan 10 '17 at 18:42















          @James Draper Thank you James. It was a good reminder.

          – Joshua
          Jan 10 '17 at 18:48





          @James Draper Thank you James. It was a good reminder.

          – Joshua
          Jan 10 '17 at 18:48











          3














          Just in case someone comes here in future, there is another pythonic way to do it. First you need to create the regex and then then filter



          import re

          inilist =["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          regex = re.compile(r'.*cat')
          selectobj = filter(regex.search, inilist)
          selectobj


          results:



          ['cat', 'wildcat', 'thundercat']





          share|improve this answer
























          • That's literally what the accepted answer suggests

            – leoluk
            Nov 14 '18 at 12:31











          • @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

            – enter_display_name_here
            Jan 15 at 15:42
















          3














          Just in case someone comes here in future, there is another pythonic way to do it. First you need to create the regex and then then filter



          import re

          inilist =["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          regex = re.compile(r'.*cat')
          selectobj = filter(regex.search, inilist)
          selectobj


          results:



          ['cat', 'wildcat', 'thundercat']





          share|improve this answer
























          • That's literally what the accepted answer suggests

            – leoluk
            Nov 14 '18 at 12:31











          • @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

            – enter_display_name_here
            Jan 15 at 15:42














          3












          3








          3







          Just in case someone comes here in future, there is another pythonic way to do it. First you need to create the regex and then then filter



          import re

          inilist =["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          regex = re.compile(r'.*cat')
          selectobj = filter(regex.search, inilist)
          selectobj


          results:



          ['cat', 'wildcat', 'thundercat']





          share|improve this answer













          Just in case someone comes here in future, there is another pythonic way to do it. First you need to create the regex and then then filter



          import re

          inilist =["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
          regex = re.compile(r'.*cat')
          selectobj = filter(regex.search, inilist)
          selectobj


          results:



          ['cat', 'wildcat', 'thundercat']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 9:51









          MEdwinMEdwin

          964114




          964114













          • That's literally what the accepted answer suggests

            – leoluk
            Nov 14 '18 at 12:31











          • @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

            – enter_display_name_here
            Jan 15 at 15:42



















          • That's literally what the accepted answer suggests

            – leoluk
            Nov 14 '18 at 12:31











          • @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

            – enter_display_name_here
            Jan 15 at 15:42

















          That's literally what the accepted answer suggests

          – leoluk
          Nov 14 '18 at 12:31





          That's literally what the accepted answer suggests

          – leoluk
          Nov 14 '18 at 12:31













          @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

          – enter_display_name_here
          Jan 15 at 15:42





          @leoluk Yes, but it shows greater detail and is probably more useful to those who ask questions vs answer questions on SO. You have 9K reputation! Of course you don't need any other details! :)

          – enter_display_name_here
          Jan 15 at 15:42


















          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%2f3640359%2fregular-expressions-search-in-list%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.

          Error while running script in elastic search , gateway timeout

          Adding quotations to stringified JSON object values