Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.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,我需要匹配和解析文件中的数据,该文件如下所示: 4801-1-21-652-1-282098 4801-1-21-652-2-282098 4801-1-21-652-3-282098 4801-1-21-652-4-282098 4801-1-21-652-5-282098 但我在下面写的模式似乎不起作用。有人能帮我理解为什么吗 final String patternStr = "(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)"; final Patte

我需要匹配和解析文件中的数据,该文件如下所示:

4801-1-21-652-1-282098
4801-1-21-652-2-282098
4801-1-21-652-3-282098
4801-1-21-652-4-282098
4801-1-21-652-5-282098
但我在下面写的模式似乎不起作用。有人能帮我理解为什么吗

final String patternStr = "(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)";
final Pattern p = Pattern.compile(patternStr);

while ((this.currentLine = this.reader.readLine()) != null) {
    final Matcher m = p.matcher(this.currentLine);
    if (m.matches()) {
        System.out.println("SUCCESS");
    }
}

您是否尝试将
-
转义为
\-

它看起来是正确的。 你的台词可能有些奇怪。寻找一些额外的空格和换行符

试试这个:

final Matcher m = p.matcher(this.currentLine.trim());

数据中有空白

 4801-1-21-652-1-282098
 4801-1-21-652-2-282098
 4801-1-21-652-3-282098
 4801-1-21-652-4-282098
 4801-1-21-652-5-282098

final String patternStr = "\\s*(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)";

它应该会起作用。确保没有不可见的字符,您可以修剪每一行。您可以将代码细化为:

final String patternStr = "(\\d{4})-(\\d{1})-(\\d{2})-(\\d{3})-(\\d{1})-(\\d{6})";

啊哈,邪恶的隐形空格再次出现:-)