How to make a group mandatory if another group is found more than once

Here is my regex:

^((([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 one (([a-zA-Z0-9_\/-]+)[ ])+((\bPHONE_NUMBER\b)|(\b(IP|EMAIL)_ADDRESS\b)) after the first .

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

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

How can i achieve this?

+5
source share
2 answers

Yes you can do it. To do this, use Recursive Regular Expression .

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

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

Description

  • (?1) is a recursive regex to repeat the regex pattern of group 1. If you want to make a recursive regex for the entire string, use (?R) , but you cannot use the start anchor ^ .
  • (;|$) matched regular expression must end with either ; or end of line $ .
  • Use \s for spaces instead of [ ] .
  • ;* and [;]* - this is the same.

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

+1
source

Duplication is ugly in general, but in such cases the most effective way is to repeat the pattern:

 FOO(;FOO)+ 

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

0
source

Source: https://habr.com/ru/post/1247793/


All Articles