Search code examples
pythonregexregex-group

Regex for similar string


I have a string which can be :

X=Y 

or

X

Here X and Y can be any word containing alphabets.

I want that when string is X=Y then X should in group 1 and Y in group 2

but when string is X then X should be in group 2.

So far I am able to get only this :

(\w+)=(\w+)

What should be the right regex for it?


Solution

  • To match alphabets, you need to use [a-zA-Z] (to match any ASCII letter) or [^\W\d_] (this matches any Unicode letter), not \w that matches letters, digits or underscores and some more chars by default in Python 3.x.

    You need

    ^(?:([A-Za-z]+)=)?([A-Za-z]+)$
    

    Or

    ^(?:([A-Za-z]+)=)?([A-Za-z]+)\Z
    

    See the regex demo

    Details

    • ^ - start of string
    • (?:([A-Za-z]+)=)? - an optional non-capturing group matching 1 or 0 occurrences of:
      • ([A-Za-z]+) - Group 1: one or more letters
      • = - a = char
    • ([A-Za-z]+) - Group 2: one or more letters
    • \Z - the very end of string ($ matches the end of string position).