有人能提供一个正则表达式,用于匹配长度在1到17之间的数字,并且可选地包含最多4位小数?长度为17包括特征和小数部分。
编辑:
长度为17不包括小数点。
有效示例:
12345678901234567 1234567890123.4567 123456789012345.67 12.34
无效示例:
12345678901234.5678(数字长度= 18)
谢谢。
有人能提供一个正则表达式,用于匹配长度在1到17之间的数字,并且可选地包含最多4位小数?长度为17包括特征和小数部分。
编辑:
长度为17不包括小数点。
有效示例:
12345678901234567 1234567890123.4567 123456789012345.67 12.34
无效示例:
12345678901234.5678(数字长度= 18)
谢谢。
^\d{17}$|^\d{13}(?=.{5}$)\d*\.\d*\d$
正则表达式解释:
^\d{17}$ //A string of 17 digits
| //or
^\d{13} //13 digits followed by
(?=.{5}$) //5 characters, of which
\d*\.\d* //one is a decimal point and others are digits
\d$ //and the last one is a digit
好的,我尽力了:
/^\d{1,17}$|(?=^.{1,18}$)^\d+\.\d{1,4}$/
基本上,匹配1-17位数字或长度为1-18的由两组数字用句点分隔而成的字符串。右侧的数字只能包含1-4个数字。
不要完全依赖正则表达式来解决问题。在大多数编程语言中,这个问题变得几乎微不足道,并且这样做将更容易让您编写、验证、测试和维护。当然,您仍然可以使用正则表达式来部分解决问题,但并非必须。伪代码:
m = re.match(r"(?P<before>[0-9]+)(?P<after>\.[0-9]{1,4})?$", input_string)
if not m:
return "no match"
before, after = m.group("before", "after")
after = after[1:] if after else "" # remove period or set to empty string
if len(before) + len(after) > 17:
return "incorrect length"
return "valid"
虽然不是特别美观,但由于可能性很少(0、1、2、3、4位尾数),我可能会将它们全部列出:
\d{17}|\d{16}\.\d{1}|\d{15}\.\d{2}|\d{14}\.\d{3}|\d{13}\.\d{4}
在你喜欢的编程语言中,你可以进行一些逻辑检查,例如Python。
num="1234567890133.3456"
if "." in num and len(num)==17 :
n=num.split(".")
if len(n[1])>4:
print "cannot have more than 4 decimal places"
elif len(n)==2 and n[0].isdigit() and n[1].isdigit():
print "yes, decimal"
elif len(num)==17 and num.isdigit():
print "%s is number with no decimal and is exactly 17 digits." % num
else:
print "%s not ok, check length is 17" % num
我从以上的优秀解决方案中创建了这个正则表达式。希望它能帮助到任何人。如果您发现其中有任何错误,请告诉我。
String decimalRegex =""+
"^(?!0[\d,])\+?" + // ^ 数字开始
"(\d{0,"+size+"}|" + // 没有组符号的数字值 | (或者)
"(\d{0,"+rem(size,groupSize)+"},)?"+
"(\d{0,"+groupSize+"},) {0,"+div(size,groupSize)+"}\d{"+groupSize+"})" + // 带有组符号的数字值
"((([a-zA-Z]{0,2}|\"|\')\s?\+?)|\.)"+
"(\d{0,"+scale+"})?" + // 没有组符号的小数值
"(\s?([a-zA-Z]{0,2}|\"|\'))$"; // 结尾
private int rem(int size,int groupSize ){
int rem = (size - groupSize)%groupSize;
return rem;
}
private int div(int size,int groupSize ){
int div = (size - groupSize)/groupSize;
return div;
}