5

Here is my regex so far :

^((([a-zA-Z0-9_\/-]+)[ ])+((\bPHONE_NUMBER\b)|(\b(IP|EMAIL)_ADDRESS\b))[ ]*[;]*[ ]*)+$

I would like to make at least one ; mandatory if I found another (([a-zA-Z0-9_\/-]+)[ ])+((\bPHONE_NUMBER\b)|(\b(IP|EMAIL)_ADDRESS\b)) after the first one.

/tests/phone PHONE_NUMBER ; /tests/IP IP_ADDRESS should match.

/tests/phone PHONE_NUMBER /tests/IP IP_ADDRESS should not match.

How can I achieve that ?

Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
Roger
  • 657
  • 5
  • 18

2 Answers2

1

Yup, you can do that. Use Recursive Regex for that.

^(((\s*(([\w_\/-]+)\s)((\bPHONE_NUMBER\b)|(\b(IP|EMAIL)_ADDRESS\b))\s*))(;|$)(?1)*)

https://regex101.com/r/dE2nK2/3

Explanation

  1. (?1) is a recursive regex to repeat the regex pattern of group 1. If you want to do recursive regex for the whole string, use (?R), but you won't be able to use beginning anchor ^.
  2. (;|$) the matched regex should be ended with either ; or the end of the string $.
  3. Use \s for whitespace instead of [ ].
  4. ;* and [;]* is same.

You can learn more about the recursive regex here: http://www.rexegg.com/regex-recursion.html

Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
0

Duplicating is ugly in general, but in cases like this the most efficient way is repeating the pattern:

FOO(;FOO)+

(Replace FOO with your (([a-zA-Z0-9_\/-]+)[ ])+((\bPHONE_NUMBER\b)|(\b(IP|EMAIL)_ADDRESS\b)) + some whitespaces if needed)

Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34