Reputation: 377
I have a problem with the Regex-If-then-else logic:
I am trying to achieve the following:
If the string contains the substring PubDSK
then do the Regex Expression
^[\s\S]{24}(?=.{10}([\s\S]*))0*(.*?)(?=\1)[\s\S]*
If it does NOT contain the substring PubDSK
then do a different Regex Expression, namely ^[\s\S]{48}(?=.{10}([\s\S]*))0*(.*?)(?=\1)[\s\S]*
I am using this Regex Expression (?(?=^.*PubDSK.*$)^[\s\S]{24}(?=.{10}([\s\S]*))0*(.*?)(?=\1)[\s\S]*|^[\s\S]{48}(?=.{10}([\s\S]*))0*(.*?)(?=\1)[\s\S]*)
The affirmative case works great: https://regex101.com/r/ab9yOv/
BUT the non-affirmative case, doesn't do the trick: https://regex101.com/r/azxGvh/1
I assume it doesn't match so it cannot do the replacement?? How can I tell the regex to do the replacement on the complete string in the ELSE case?
I understand, that this problem can be easily solved with any other programming language, but for this use case I can only use pure regex...
Upvotes: 2
Views: 111
Reputation: 626825
The second \1
backreference refers to the first capturing group of the entire regex. So, it does not refer to the right capturing group defined in the else pattern part. In fact, the second \1
must be replaced with \3
as it refers to the third capturing group.
Also, note that (?=\1)
and (?=\3)
lookaheads make little sense here as they are followed with [\s\S]*
consuming patterns. Just remove the lookahead pattern and use consuming ones.
The fixed pattern looks like
(?(?=^.*PubDSK.*$)^[\s\S]{24}(?=.{10}([\s\S]*))0*(.*?)\1[\s\S]*|^[\s\S]{48}(?=.{10}([\s\S]*))0*(.*?)\3[\s\S]*)
See the regex demo.
Upvotes: 3