Java 处理字符串以供正则表达式使用
我有自己的Java 处理字符串以供正则表达式使用,java,regex,Java,Regex,我有自己的indexOf函数 private static int indexOf(String target, String pattern){ Pattern p = Pattern.compile(pattern); Matcher matcher = p.matcher(target); if(matcher.find()){ return matcher.start(); } return -1; } 此函数接收用户
indexOf
函数
private static int indexOf(String target, String pattern){
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(target);
if(matcher.find()){
return matcher.start();
}
return -1;
}
此函数接收用户提供的模式
,并查看模式
是否存在于目标
字符串中。有时,用户可以在字符串中包含正则表达式字符,如***hello world
,这会导致函数在线程“main”java.util.regex.PatternSyntaxException:hangling meta character'*'中返回异常
错误
如何处理用户生成的字符串以克服此类错误?使用
注意:这假设传入的不是真正的正则表达式
公共静态字符串引号(字符串s)
返回指定字符串的文本模式字符串。这种方法
生成一个字符串,该字符串可用于创建
匹配字符串s,就像它是一个文本模式一样
将给出输入序列中的元字符或转义序列
没有特别的意义
它们应该能够包含正确使用的正则表达式字符吗?@ExplosionPills它们不是。。我希望正则表达式字符的处理方式与
s
a
b
等相同。“我有自己的indexOf函数。”为什么?
Pattern p = Pattern.compile(Pattern.quote(pattern));