0

I'm filtering out string using below regex

^(?!.*(P1 | P2)).*groupName.*$

Here group name is specific string which I replace at run time. This regex is already running fine.

I've two input strings which needs to pass through from this regex. Can't change ^(?!.*(P1 | P2)) part of regex, so would like to change regex after this part only. Its a very generic regex which is being used at so many places, so I have only place to have changes is groupName part of regex. Is there any way where only 2 string could pass through this regex ?

1) ADMIN-P3-UI-READ-ONLY
2) ADMIN-P3-READ-ONLY

In regex groupName is a just a variable which will be replaced at run time with required string. In this case I want 2 string to be passed, so groupName part can be replaced with READ-ONLY but it will pass 1 string too.

Can anyone suggest on this how to make this work ?

Kate
  • 275
  • 1
  • 4
  • 15

2 Answers2

0

You could use negative lookBehind:

(?<!UI-)READ-ONLY

so there must be no UI- before READ-ONLY

Turo
  • 4,724
  • 2
  • 14
  • 27
0

You can add another lookahead at the very start of your pattern to further restrict what it matches because your pattern is of the "match-everything-but" type.

So, it may look like

String extraCondition = "^(?!.*UI)";
String regex = "^(?!.*(P1|P2)).*READ-ONLY.*$";
String finalRegex = extraCondition + regex;

The pattern will look like

^(?!.*UI)^(?!.*(P1|P2)).*READ-ONLY.*$

matching

  • ^(?!.*UI) - no UI after any zero or more chars other than line break chars as many as possible from the start of string
  • ^(?!.*(P1|P2)) - no P1 nor P2 after any zero or more chars other than line break chars as many as possible from the start of string
  • .*READ-ONLY - any zero or more chars other than line break chars as many as possible and then READ-ONLY
  • .*$ - the rest of the string. Note you may safely remove $ here unless you want to make sure there are no extra lines in the input string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563