Home > front end >  check if particular string is present in a sentence
check if particular string is present in a sentence

Time:01-21

I'm trying to check some string in a row in a sentence using if condition but i'm not getting the expected the output. I've also tried with the Regex pattern but that is also not helping me out. Can anyone help me with this? My value for string changes everytime so not sure if this is the problem.

r="Carnival: monitor service-eu Beta cloudwatch_module" 
  if "Carnival: monitor service-eu Beta" in r:
            test_string="EU"
            test_string1="eu"
        elif "Carnival: monitor service-na Beta" in r:
            test_string="NA"
            test_string1="na"
        elif "Carnival: monitor service-fe Beta" in r:
            test_string="FE"
            test_string1="fe"
        else:
            print("None found")

With regex something like this.

but this is also not working.

re_pattern = r'\b(?:service-eu|Beta|monitor|Carnival)\b'
new_= re.findall(re_pattern, r)
new1_=new_[2]

CodePudding user response:

If isn't necessary use this short_description function, I suggest you use the find function:

if r.find("Carnival: monitor service-eu Beta") != -1:
 test_string="EU"
 test_string1="eu"
elif r.find("Carnival: monitor service-na Beta") != -1:
 test_string="NA"
 test_string1="na"
elif r.find("Carnival: monitor service-fe Beta") != -1:
 test_string="FE"
 test_string1="fe"
else:
 print("None found")

CodePudding user response:

I'm not 100% sure I understand your problem, but hopefully this helps:


import re

def get_string(r):
    return re.findall(r"service-[a-z]{2}",r)[0][-2:]

get_string("Carnival: monitor service-na Beta")
>>> 'na'
get_string("Carnival: monitor service-fe Beta")
>>> 'fe'

Here, [a-z]{2} means any word that contains lowercase letters with a length of 2.

CodePudding user response:

You can use a pattern with a capture group and .upper() for the group value.

\bCarnival: monitor service-([a-z]{2}) Beta\b

See the capture group value at the regex 101 demo and a Python demo.

Example

import re

pattern = r"\bCarnival: monitor service-([a-z]{2}) Beta\b"
r = "Carnival: monitor service-eu Beta cloudwatch_module"
m = re.search(pattern, r)
if m:
    test_string1 = m.group(1)
    test_string = test_string1.upper()

    print(test_string)
    print(test_string1)

Output

EU
eu
  • Related