alex747
alex747

Reputation: 149

Python regex expression example

I have an input that is valid if it has this parts:

  1. starts with letters(upper and lower), numbers and some of the following characters (!,@,#,$,?)
  2. begins with = and contains only of numbers
  3. begins with "<<" and may contain anything

example: !!Hel@#lo!#=7<<vbnfhfg

what is the right regex expression in python to identify if the input is valid? I am trying with pattern= r"([a-zA-Z0-9|!|@|#|$|?]{2,})([=]{1})([0-9]{1})([<]{2})([a-zA-Z0-9]{1,})/+"

but apparently am wrong.

Upvotes: 1

Views: 219

Answers (1)

Verbindungsfehler
Verbindungsfehler

Reputation: 36

For testing regex I can really recommend regex101. Makes it much easier to understand what your regex is doing and what strings it matches.

Now, for your regex pattern and the example you provided you need to remove the /+ in the end. Then it matches your example string. However, it splits it into four capture groups and not into three as I understand you want to have from your list. To split it into four caputre groups you could use this:

"([a-zA-Z0-9!@#$?]{2,})([=]{1}[0-9]+)(<<.*)"

This returns the capture groups:

  1. !!Hel@#lo!#
  2. =7
  3. <<vbnfhfg

Notice I simplified your last group a little bit, using a dot instead of the list of characters. A dot matches anything, so change that back to your approach in case you don't want to match special characters.

Here is a link to your regex in regex101: link.

Upvotes: 1

Related Questions