带连字符的 Java 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4475619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regular expression with hyphen
提问by Amir Afghani
I need to match and parse data in a file that looks like:
我需要匹配和解析如下文件中的数据:
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
but the pattern I wrote below does not seem to work. Can someone help me understand why?
但我在下面写的模式似乎不起作用。有人可以帮我理解为什么吗?
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");
}
}
采纳答案by Roman
It looks correct. Something odd is conatined in your lines, probably. Look for some extra spaces and line breaks.
它看起来是正确的。您的台词中可能包含一些奇怪的东西。寻找一些额外的空格和换行符。
Try this:
尝试这个:
final Matcher m = p.matcher(this.currentLine.trim());
回答by Jason S
Have you tried escaping the -
as \\-
?
你有没有试过逃避-
as \\-
?
回答by Amir Afghani
There is white space in the data
数据中有空格
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+)";
回答by fastcodejava
It should work. Make sure there is no invisible characters, you an trim each line. You can refine the code as :
它应该工作。确保没有不可见的字符,你修剪每一行。您可以将代码细化为:
final String patternStr = "(\d{4})-(\d{1})-(\d{2})-(\d{3})-(\d{1})-(\d{6})";