我正在创建一个函数,从输入字符串中删除非法通配符模式。如果可能的话,理想的解决方案应该使用单个正则表达式。
非法通配符模式为:%%
和 %_%
。其中的每个实例都应替换为 %
。
这就是问题所在...我正在尝试通过针对各种输入运行该函数来执行一些模糊测试,以尝试实现它并破坏它。
它在大多数情况下都有效;但是,对于复杂的输入,则不然。
此问题的其余部分已更新:
以下输入应返回空字符串(不是详尽的列表):
以下输入应返回%
(不是详尽的列表)。
- %_%
- %%
- %%_%%
- %_%%%
- %%_%_%
- %%_%%%_%%%_%
在某些情况下,输入中还会有其他字符...例如:
- Foo123%_%
- 应返回“Foo123%”
- B4r$%_%
- 应返回“B4r$%”
- B4rs%%_%
- 应返回“B4rs%”
- %%Lorem_%%
- 应返回“%Lorem_%”
我尝试使用几种不同的模式,但我的测试失败了。
String input = "%_%%%%_%%%_%";
// old method:
public static String ancientMethod1(String input){
if (input == null)
return "";
return input.replaceAll("%_%", "").replaceAll("%%", ""); // Output: ""
}
// Attempt 1:
// Doesn't quite work right.
// "A%%" is returned as "A%%" instead of "A%"
public static String newMethod1(String input) {
String result = input;
while (result.contains("%%") || result.contains("%_%"))
result = result.replaceAll("%%","%").replaceAll("%_%","%");
if (result.equals("%"))
return "";
return input;
}
// Attempt 2:
// Succeeds, but I would like to simplify this:
public static String newMethod2(String input) {
if (input == null)
return "";
String illegalPattern1 = "%%";
String illegalPattern2 = "%_%";
String result = input;
while (result.contains(illegalPattern1) || result.contains(illegalPattern2)) {
result = result.replace(illegalPattern1, "%");
result = result.replace(illegalPattern2, "%");
}
if (result.equals("%") || result.equals("_"))
return "";
return result;
}
这是一个更完整的定义示例,说明我如何使用它:https://gist.github.com/sometowngeek/697c839a1bf1c9ee58be283b1396cf2e
最佳答案
此正则表达式字符串与您的所有示例相匹配:
"%(?:_?%)+"
它匹配由“%”字符组成的字符串,后跟一个或多个由零个或一个“_”字符和一个“%”字符组成的序列(接近直译),这是表达我所做的另一种方式在注释中:“一系列‘%’和‘_’字符,以‘%’开头和结尾,并且不包含两个连续的‘_’字符”。
关于java - 如何用单个正则表达式模式替换过多的 SQL 通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453348/