上下文:我找到了一个匹配由“$”字符分隔的三个整数的解决方案,如下所示:
String toMatch = "123$53$12"; //Returns true
String toMatch2 = "123$0$12"; //Returns false
String toMatch3 = "0$53$12"; //Returns false
String toMatch4 = "123$53$0"; //Returns false
System.out.println(toMatch.matches("\\d+.*\\d+.*\\d+") && !toMatch.matches([^0-9]*0[^0-9]*"));
问题:我想要实现的是:
String toMatch = "123.43$.03$123.0"; //Returns true
String toMatch2 = "123$000000$12"; //Returns false
String toMatch3 = "0.0000$53$12"; //Returns false
String toMatch4 = "123$53$.000"; //Returns false
本质上,我想要的是一个正则表达式,匹配由“$”字符分隔的 3 个数字,如果由 Double.parseDouble()
方法解析,每个数字都是正非零 double 。
最佳答案
如果我理解正确,我认为这会起作用:
^(?!\\$)((^|\\$)(?=[^$]*[1-9])(\\d+(\\.\\d*)?|(\\.\\d*)?\\d+)){3}$
下面是解释:
^(?!\\$)
:匹配的开头后面不能跟“$”{3}
:以下模式必须重复 3 次(^|\\$)
:模式以字符串开头或以“$”开头(不是两者,如上所述)(?=[^$]*[1-9])
:在下一个最终的“$”之前必须有一个非 0 数字(\\d+(\\.\\d*)?|(\\.\\d*)?\\d+)
:允许的数字格式为\d+(\.\d*)?
或(\.\d*)?\d+
$
:结束
参见here演示
扩展表达式(如果您不相信重复技巧)是:
^(?=[^$]*[1-9])(\\d+(\\.\\d*)?|(\\.\\d*)?\\d+)\\$(?=[^$]*[1-9])(\\d+(\\.\\d*)?|(\\.\\d*)?\\d+)\\$(?=[^$]*[1-9])(\\d+(\\.\\d*)?|(\\.\\d*)?\\d+)$
关于java - 用于匹配由 "$"字符分隔的正非零 double 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820333/