Kanchon Gharami
Kanchon Gharami

Reputation: 949

Regular expression pattern matching with required conditions

How can I write a regex pattern that matches the following pattern:

  1. Starting with 0/2/a/Q.
  2. Must end with S/d.
  3. Must contain at least two 0s.
  4. Only contain Alphanumeric characters and the only special character $ (Dollar sign).

I have tried this out, but the two 0s condition is not satisfied by my code:

import re


data = '''
    Hello everyone, good evening, I am kanchon and I am from RUET. Now I am writing my assignment for automata code and trying to solve out this problem.
    Some dummy content line is following:
    022jdshjgh$dgdg Quite$stupid this is enough
'''
date_pattern = re.compile(r'[02aQ][a-zA-Z0-9$]+[Sd]')
dates = date_pattern.findall(data)

print(dates)

Upvotes: 0

Views: 52

Answers (1)

dawg
dawg

Reputation: 104034

Take your description and add a lookahead:

^(?=.*?0.*0)[02aQ][a-zA-Z0-9$]+[Sd]$

Demo

That works for a single string on a single line.

For a target in a text, you would add something to look for standalone words. I will leave that as an excise to the OP.

Upvotes: 1

Related Questions