Java中的Scanner useDelimiter()方法。

huangapple go评论69阅读模式
英文:

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(&quot;\\.|(?&lt;=\\d{2})&quot;);
    System.out.print(&quot;Enter dms: &quot;);
    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

问题在于正则表达式 \.|(?&lt;=\d{2}) 匹配了 12 之间的位置,因为在当前位置 36.521|2(由字符 | 表示),左边有两个数字(字符串 21)。

您可以将正则表达式更改为以下内容:

\.|(?&lt;=\.\d{2})

这样可以强制要求只有 . 字符本身或位置 36.52|12 才是有效位置,在位置 36.521|2 中将不再匹配,因为在 52 之间缺少 . 字符。

您可以使用 https://regex101.com/r/fL3kyA/1 上的可视化工具来检查您的正则表达式问题:

Java中的Scanner useDelimiter()方法。

如您所见,通过粉色的条形图,它找到了三个位置,尽管您只想要一个位置。

英文:

The problem is that the regex \.|(?&lt;=\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:

\.|(?&lt;=\.\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:

Java中的Scanner useDelimiter()方法。

As you see by the pink bars, it finds three positions, even though you only want one.

huangapple
  • 本文由 发表于 2020年10月19日 02:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64416960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定