0

I'm having a pattern where it should be matched any where in the input text given

text_pattrn = """ Todays weather | Todays weather is | weather | Todays weather condition | weather condition """

input_text = """ Every one is eagerly waiting for the final match to be happened in this ground and all eyes on sky as todays weather condition is cloudy and rain may affect the game play"""

match = re.search(text_pattrn,input_text)

There are several text patterns repeated, for example "weather" is redundant because "Todays weather" already matches "weather" . Any solution to optimize the code would really helps a lot.

1
  • 1
    Why not just make the pattern whether? That word is common to all the patterns, so you can just check for that, unless you need to use the matched text for something else later. (Also, note that the correct spelling for your example sentence is "weather", not "whether".) Commented Jan 6, 2023 at 6:01

1 Answer 1

1

You could make the pattern case insensitive using re.I, make some of the parts optional so that you can shorted the alternatives and put all the alternatives in a non capture group adding word boundaries to the left and right (or keep the spaces if you want)

\b(?:Todays weather(?: is)?|weather|(?:Todays )?weather condition)\b

See a regex 101 demo.

If you want to print all matches, you can use re.findall

import re

text_pattrn = r"\b(?:Todays weather(?: is)?|weather|(?:Todays )?weather condition)\b"
input_text = """ Every one is eagerly waiting for the final match to be happened in this ground and all eyes on sky as todays weather condition is cloudy and rain may affect the game play"""
print(re.findall(text_pattrn, input_text, re.I))

Output

['todays weather']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.