annedroiid
annedroiid

Reputation: 6637

Having trouble building a regular expression

I am trying to build a regular expression that has the following rules:

Legitimate cases would be:

If this needs more clarification just let me know, it's kind of hard to explain it.

I currently have this for my regular expression:

(\w+\.)*(\*|\w+)\=\w+

Which correctly validates the given examples, however it matches ".*=INFO" which should be invalid. Anyone know how I can get it to not match this string?

Upvotes: 3

Views: 49

Answers (2)

Markus Laire
Markus Laire

Reputation: 2947

^(\*|\w+(\.\w+)*(\.\*)?)\=\w+$

This handles separately cases which start with an asterisk and those which start with a character, since I wasn't able to combine them.

^          begin
(
 \*        asterisk
|            or
 \w+       first word
 (\.\w+)*  optionally more words, separated by dot
 (\.\*)?   optional dot + asterisk
)
\=         equals
\w+
$          end

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

For convenience, let's call an asterisk or a word of any non-zero length a token. So, word and * are "tokens".
We can describe it using regular expression as (\*|\w+).

Now, we want regex which matches the following:

  • begining of a line
  • a token
  • 0 or more combinations of (dot + token)
  • equals sign and a non-empty word
  • end of a line

As result, we have something like

^(\*|\w+)(\.(\*|\w+))*=\w+$

which is

^         (\*|\w+)       (\.(\*|\w+))*               =\w+$   
begin     token          0 or more (dot + token)     equals, word and end

Regex101 demo

Upvotes: 1

Related Questions