[英]regex to filter out string
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.无法更改正则表达式的^(?..*(P1 | P2))
部分,因此只想在此部分之后更改正则表达式。 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.它是一个非常通用的正则表达式,在很多地方都在使用,所以我唯一需要更改的地方是正则表达式的groupName
部分。 Is there any way where only 2
string could pass through this regex?有没有办法只有2
字符串可以通过这个正则表达式?
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.在正则表达式中, groupName
只是一个变量,它将在运行时替换为所需的字符串。 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.在这种情况下,我希望传递2
字符串,因此可以将groupName
部分替换为READ-ONLY
但它也会传递1
字符串。
Can anyone suggest on this how to make this work?任何人都可以建议如何进行这项工作吗?
You could use negative lookBehind:您可以使用负向后视:
(?<!UI-)READ-ONLY
so there must be no UI- before READ-ONLY所以在 READ-ONLY 之前必须没有 UI-
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 ^(?..*UI)
- 除了换行符之外的任何零个或多个字符之后没有UI
从字符串的开头尽可能多^(?..*(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 ^(?..*(P1|P2))
- 除了换行符之外的任何零个或多个字符之后,从字符串的开头起尽可能多的没有P1
或P2
.*READ-ONLY
- any zero or more chars other than line break chars as many as possible and then READ-ONLY
.*READ-ONLY
- 除换行符之外的任何零个或多个字符尽可能多,然后READ-ONLY
.*$
- the rest of the string. .*$
- 字符串的 rest。 Note you may safely remove $
here unless you want to make sure there are no extra lines in the input string.请注意,除非您想确保输入字符串中没有多余的行,否则您可以在此处安全地删除$
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.