polapts
polapts

Reputation: 5793

Python how to find a substring in a string and print the whole string containing the substring

I am struggling to find a solution to print a string which contains a particular substring. So e.g. I have a string

mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"

I want to search for "mon" in the string above and print "mon_this_is_monday" but not sure how to do it

I tried doing

    pattern = re.compile('mon_')
    try:
        match = re.search(pattern, mystr).group(0)
        print(match)
    except AttributeError:
        print('No match')

but this this just gives mon_ as output for match. How do I get the whole string "mon_this_is_monday" as output?

Upvotes: 1

Views: 2102

Answers (3)

Shrikant Gourh
Shrikant Gourh

Reputation: 88

you can also do a search on regex

import re


mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"

abc = re.search(r"\b(\w*mon\w*)\b",mystr)

print(abc.group(0))

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

We could try using re.findall with the pattern \b\w*mon\w*\b:

mystr = "<tag> name = mon_this_is_monday value = 10 </tag>"
matches = re.findall(r'\b\w*mon\w*\b', mystr)
print(matches)

This prints:

['mon_this_is_monday']

The regex pattern matches:

\b   a word boundary (i.e. the start of the word)
\w*  zero or more word characters (letters, numbers, or underscore)
mon  the literal text 'mon'
\w*  zero or more word characters, again
\b   another word boundary (the end of the word)

Upvotes: 4

Louis Saglio
Louis Saglio

Reputation: 1148

print([string for string in mystr.split(" ") if "mon" in string])

Upvotes: 3

Related Questions