Unable to generate regex for the string

Viewed 71

I have a string abc-[|123|243|]-xyz-[|432|567|] and I want to generate a regex that matches the specific string.

The regex should be tested against the following examples and with the specific result.

Exp 1: abc-[|123|234|]-xyz-[|432|567|] (123 is present in [|123|243|])

Result : Match

Exp 2: xyz-[|123|243|]-abc-[|432|567|] (order of abc and xyz interchanged)

Result : No match

Exp 3: abc-[|243|563|]-xyz-[|432|567|] (243 and 432 are present)

Result : Match

Exp 4: xyz-[|143|434|]-abc-[|432|999|] ([|148|434|] not match of any number in [|123|243|])

Result : No match

I tried creating a regex but its only working in the exact case and not working in other cases.

abc-\[\|123\||243\|\]-xyz-\[\|432\||567\|\]

1 Answers

You can use

^abc-\[\|(?:123|243)\|\d+\|\]-xyz-\[\|432\|\d+\|\]$

See the regex demo.

Details

  • ^ - start of string
  • abc-\[\| - abc-[|
  • (?:123|243) - either 123 or 243
  • \| - a |
  • \d+ - 1+ digits
  • \|\]-xyz-\[\|432\| - a |]-xyz-[|432| text
  • \d+ - 1+ digits
  • \|\] - a |] text
  • $ - end of string
Related