Regex for similar string

Viewed 148

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?

2 Answers

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).

You almost had it with your original regex.

It just needs a couple of tweaks:

^(\w+)(=(\w+))?$
  • ^ = start of string
  • (\w+) = 1st capture group matching any word like character (including numbers) as many times as possible.
  • (=...)? = everything inside this 2nd capture group (starting with "=") is optional
  • 2nd (\w+) = 3rd capture group matching the same stuff as the first one
  • $ = end of string

update

My answer does not actually answer the original question because the "X" string does not land "X" in the second answer group.

I considered deleting the answer, but I'm going to keep it up for the sake of other visitors on the site who are looking for a simpler answer that does not require "X" to specifically be in the second capture group.

Also, maybe the original asker would rather have a simpler regex and modify their code to work with the regex instead of making a regex to work with the code.

Related