Battle_Slug
Battle_Slug

Reputation: 2105

Regex for matching sequence followed by either of two another sequences

I am trying to write regex for java for matching following string examples:

my_phrases=[phrase1, phrase2]
my_phrases=[phrase2, phrase1]

So the sequence my_phrases= followed by the sequence of phrase1 and phrase2 in any order should be matched. What I did:

 ^my_phrases.?(phrase1,phrase2|phrase2,phrase1)$

It doesn't work. Could you help?

Upvotes: 0

Views: 502

Answers (3)

Mario Santini
Mario Santini

Reputation: 3003

This is something generic:

/^(my_phrases=\[([^,]+),\s([^,]+)\])$/gm

MATCH 1

  1. [0-29] my_phrases=[phrase1, phrase2]
  2. [12-19] phrase1
  3. [21-28] phrase2

MATCH 2

  1. [30-59] my_phrases=[phrase2, phrase1]
  2. [42-49] phrase2
  3. [51-58] phrase1

And this is a bit specific:

/^(my_phrases=\[(phrase1|phrase2),\s(phrase1|phrase2)\])$/gm

MATCH 1

  1. [0-29] my_phrases=[phrase1, phrase2]
  2. [12-19] phrase1
  3. [21-28] phrase2

MATCH 2

  1. [30-59] my_phrases=[phrase2, phrase1]
  2. [42-49] phrase2
  3. [51-58] phrase1

Upvotes: 1

T33C
T33C

Reputation: 4429

Something like this perhaps...

 ^my_phrases=\[((phrase1, phrase2)|(phrase2, phrase1))\]$

Upvotes: 1

tobias_k
tobias_k

Reputation: 82929

Your regex does not work because it is not accounting for the [ and ] and for the space after the ,. You could try a regex like this:

^my_phrases.*(phrase1,\s*phrase2|phrase2,\s*phrase1).*$

But of course, the "perfect" regex depends on what exactly you want to match, e.g. whether those [ and ] etc. are actually optional or mandatory.

Upvotes: 1

Related Questions