Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 处理字符串以供正则表达式使用_Java_Regex - Fatal编程技术网

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));