转义模式中除某些元字符之外的所有字符
我想允许用户在搜索中使用 "*"
元字符,并希望使用用户通过 Pattern.compile
输入的模式。因此,我必须转义用户输入的除 *
之外的所有其他元字符。我正在使用下面的代码来完成此操作,有更好的方法吗?
private String escapePattern(String pattern) {
final String PATTERN_MATCH_ALL = ".*";
if(null == pattern || "".equals(pattern.trim())) {
return PATTERN_MATCH_ALL;
}
String remaining = pattern;
String result = "";
int index;
while((index = remaining.indexOf("*")) >= 0) {
if(index > 0) {
result += Pattern.quote(remaining.substring(0, index)) + PATTERN_MATCH_ALL;
}
if(index < remaining.length()-1) {
remaining = remaining.substring(index + 1);
} else
remaining = "";
}
return result + Pattern.quote(remaining) + PATTERN_MATCH_ALL;
}
I want to allow the user use a "*"
metachar in search and would like to use the pattern entered by user with Pattern.compile
. So I would have to escape all the other metachars that user enters except the *
. I am doing it with the below code, is there a better way of doing this?
private String escapePattern(String pattern) {
final String PATTERN_MATCH_ALL = ".*";
if(null == pattern || "".equals(pattern.trim())) {
return PATTERN_MATCH_ALL;
}
String remaining = pattern;
String result = "";
int index;
while((index = remaining.indexOf("*")) >= 0) {
if(index > 0) {
result += Pattern.quote(remaining.substring(0, index)) + PATTERN_MATCH_ALL;
}
if(index < remaining.length()-1) {
remaining = remaining.substring(index + 1);
} else
remaining = "";
}
return result + Pattern.quote(remaining) + PATTERN_MATCH_ALL;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样
How about