英文:
Java Scanner useDelimiter() Method
问题
scanner.useDelimiter("\\.|(?<=\\d{2})");
System.out.print("Enter dms: ");
degrees = scanner.next();
minutes = scanner.next();
seconds = scanner.next();
输入36.5212会导致seconds等于1,而不是seconds等于12。我应该如何更正我的scanner.useDelimiter方法?谢谢!
英文:
    scanner.useDelimiter("\\.|(?<=\\d{2})");
    System.out.print("Enter dms: ");
    degrees = scanner.next();
    minutes = scanner.next();
    seconds = scanner.next();
An input of 36.5212 returns seconds = 1, not seconds = 12. How would I correct my scanner.useDelimeter method? Thank you!
答案1
得分: 3
问题在于正则表达式 \.|(?<=\d{2}) 匹配了 1 和 2 之间的位置,因为在当前位置 36.521|2(由字符 | 表示),左边有两个数字(字符串 21)。
您可以将正则表达式更改为以下内容:
\.|(?<=\.\d{2})
这样可以强制要求只有 . 字符本身或位置 36.52|12 才是有效位置,在位置 36.521|2 中将不再匹配,因为在 5 和 2 之间缺少 . 字符。
您可以使用 https://regex101.com/r/fL3kyA/1 上的可视化工具来检查您的正则表达式问题:
如您所见,通过粉色的条形图,它找到了三个位置,尽管您只想要一个位置。
英文:
The problem is that the regex \.|(?<=\d{2}) is matching the position between the 1 and the 2, because at the position 36.521|2 (current position indicated by the | character), there are two digits to the left (the string 21).
You can change the regex to the following:
\.|(?<=\.\d{2})
This way you enforce it, that the valid positions are only the . character itself or the position 36.52|12, where there is the positive look-behind of .\d\d (the string .52). The position 36.521|2 will not match anymore because the . character is missing between 5 and 2.
You can check the issue with your regex with the visualization from https://regex101.com/r/fL3kyA/1:
As you see by the pink bars, it finds three positions, even though you only want one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论