Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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,我需要将包含文本和通配符(星号“*”)的字符串转换为包含文本和正则表达式的字符串 例如,字符串: 罐子 将转换为: 其中,[0-9a-zA-Z.-]+是替换它的正则表达式(匹配1+位数、字母字符、句点或破折号的正则表达式) 这是我的密码: // inputStr is same as first example above (containing asterisks) // strWithRegex is same as 2nd example above String strWithRege

我需要将包含文本和通配符(星号“*”)的字符串转换为包含文本和正则表达式的字符串

例如,字符串:

罐子

将转换为:

其中,
[0-9a-zA-Z.-]+
是替换它的正则表达式(匹配1+位数、字母字符、句点或破折号的正则表达式)

这是我的密码:

// inputStr is same as first example above (containing asterisks)
// strWithRegex is same as 2nd example above
String strWithRegex = inputStr.replaceAll("*", "[0-9a-zA-Z.-]+")
当我运行此命令时,我得到:

Caught: java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*
^
java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*
^
    at java_lang_String$replaceAll$2.call(Unknown Source)
    ...rest of stack trace omitted for brevity
我哪里出错了?此外,我也不能100%确定我的正则表达式是否正确,它需要匹配1+:

  • 数字(0-9);或
  • 大写/小写罗马字母字符(a-z,a-z);或
  • 期间(“.”)
  • 连字符(“-”)

方法
replaceAll()
的第一个参数是模式。由于
*
在模式中具有特殊意义,因此您必须使用
\
对其进行转义。但更简单的方法是使用
replace()
方法

编辑


顺便说一句,我通常使用
str.replace(“*”,“*”)
来枚举所有可能的字符

您应该使用
\\*
来转义
*
,因为
*
在regexCan中有一个特殊的含义,也可以用来避免过多和混淆字符串中的“`in”。@OldCurmudgeon,好主意。然而,在这种情况下,这是过分的。