Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make group mandatory if other group is found more than once

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 ?

like image 667
Roger Avatar asked Nov 08 '22 16:11

Roger


1 Answers

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

like image 185
Aminah Nuraini Avatar answered Nov 14 '22 23:11

Aminah Nuraini