skip to Main Content

I’m generating a bot that should receive telegram messages and forward them to another group after applying regex to the received message.

Regex tested in PHP and sites around the web, in theory it should work.

regex = r"⏰ Timeframe M5((s+(.*)s+){1,})⏰ Timeframe M15"
text_example = '''⏰ Timeframe M5


04:05 - EURUSD - PUT
05:15 - EURJPY - PUT
06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT

⏰ Timeframe M15

06:35 - EURGBP - PUT
07:10 - EURUSD - PUT
08:15 - EURJPY - PUT '''

reg = re.findall(regex, example_text)
print(reg)

return me
[ ]

I’ve run out of attempts..

I’ve used regex in other situations and had no problems, in this one I don’t know why it works

2

Answers


  1. If you slightly change your regex and also run it in dot all mode, it should work:

    regex = r'⏰ Timeframe M5.*?⏰ Timeframe M15'
    matches = re.findall(regex, text_example, flags=re.S)
    print(matches)
    

    This prints:

    ⏰ Timeframe M5
    
    
    04:05 - EURUSD - PUT
    05:15 - EURJPY - PUT
    06:35 - EURGBP - PUT
    07:10 - EURUSD - PUT
    08:15 - EURJPY - PUT
    
    ⏰ Timeframe M15
    
    Login or Signup to reply.
  2. The pattern does not work for the example data because you are repeating 1 or more leading AND trailing whitespace characters after .*. This will not match if you have 2 consecutive lines without for example extra spaces at the end that you do seem to have in this regex example https://regex101.com/r/gvulvK/3

    Note that the name of the initial variable is text_example

    What you might do is match the start and the end of the pattern, and in between match all lines that do not start with for example the ⏰

    ⏰ Timeframe M5s*((?:n(?!⏰).*)+)n⏰ Timeframe M15b
    

    See this regex101 demo and this regex101 demo

    import re
    
    regex = r"⏰ Timeframe M5s*((?:n(?!⏰).*)+)n⏰ Timeframe M15b"
    text_example = '''⏰ Timeframe M5
    
    
    04:05 - EURUSD - PUT
    05:15 - EURJPY - PUT
    06:35 - EURGBP - PUT
    07:10 - EURUSD - PUT
    08:15 - EURJPY - PUT
    
    ⏰ Timeframe M15
    
    06:35 - EURGBP - PUT
    07:10 - EURUSD - PUT
    08:15 - EURJPY - PUT '''
    
    reg = re.findall(regex, text_example)
    print(reg)
    

    Output

    ['n04:05 - EURUSD - PUTn05:15 - EURJPY - PUTn06:35 - EURGBP - PUTn07:10 - EURUSD - PUTn08:15 - EURJPY - PUTn']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search