-1

How to find a word by using regex?

import re

s = 'ddxx/CS12-CS13/C512/2ABC', "sss"
for i in s:
    c = re.findall('/C', i) 
    print(c)

I want to print elements which contain /C.

Expected output:

ddxx/CS12-CS13/C512/2ABC
10
  • 2
    One of the greatest challenges that beginners of any new thing face is learning the terminology. That makes it difficult to find the questions that have already been asked. In recognition of that, here is a question that should help you: stackoverflow.com/q/15374969/2988730 Commented Apr 3, 2019 at 6:05
  • Whoa, easy on the formatting there, Picasso - I'm assuming s is supposed to be a list, but you're missing the [] around it? You're not going to find /C in i, so that does not make a lot of sense either. And I'm assuming you want to print all elements containing some other element? Commented Apr 3, 2019 at 6:07
  • 4
    @Grismar. All it takes is a comma to make a tuple Commented Apr 3, 2019 at 6:08
  • 2
    Here is an exact dupe: stackoverflow.com/q/9012008/2988730 Commented Apr 3, 2019 at 6:14
  • 1
    @FailSafe that's cool - note that it works on both sides, this was a really cool thing I liked about Python when I found out: a, b = something(), something_else() works, because you can define the tuple with a comma, but you can just as easily unpack it with a comma as well. Commented Apr 4, 2019 at 0:25

2 Answers 2

2

You can do this using in without regex at all.

s = 'ddxx/CS12-CS13/C512/2ABC',"sss"
for i in s:
    if '/C' in i:  
        print(i)

This gives your desired output of:

ddxx/CS12-CS13/C512/2ABC

Using regex:

import re

s = 'ddxx/CS12-CS13/C512/2ABC',"sss"
for i in s:
    if re.search('/C', i):  
        print(i)

Gives the same output:

ddxx/CS12-CS13/C512/2ABC

Duplicate of: python's re: return True if regex contains in the string

Sign up to request clarification or add additional context in comments.

2 Comments

thanks but i want to use with regex(regular expression)
@python_learner I added an example with regex too.
1

assuming your s is a list of strings,

import re
s = ['ddxx/CS12-CS13/C512/2ABC', "sss"]
for i,string in enumerate(s):
    if len(re.findall('/C', string)) > 0 :
        print(s[i])

will give you the desired output ddxx/CS12-CS13/C512/2ABC

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.