简体   繁体   English

带点数字的正则表达式模式

[英]Regex pattern for numbers with dots

I need a regex expression for this我需要一个正则表达式

any number then .任何数字然后。 and again number and .再次编号和。

So this is valid所以这是有效的

1.3.164.1.2583.15.46
546.598.856.1.68.268.695.5955565

but

5..........
...56.5656

are not valid无效

I tried patterns like:我尝试了以下模式:

pattern = "[0-9](\\.[0-9]?*)?*";
pattern = "[0-9](\\.[0-9]?*)?$";
pattern = "[^0-9\\.]";

but none of these fulfill my requirement.但这些都不能满足我的要求。 Please help?请帮忙?

My existing code is我现有的代码是

String PATTERN="\\d+(\\.\\d+)*";
@Override
public void insertString(int arg0, String arg1, AttributeSet arg2)
{

    if(!arg1.matches(this.PATTERN))
        return;

    super.insertString(arg0, arg1, arg2);
}

Something like this should work:这样的事情应该工作:

(\\\\d+\\\\.?)+

Edit编辑

Yep, not clear from the description if a final .是的,如果最终. is allowed (assuming an initial one is not ).是允许的(假设初始的不是)。

If not:如果不:

(\\\\d+\\\\.?)*\\\\d+ or \\\\d+(\\\\.\\\\d+)* (if that seems more logical) (\\\\d+\\\\.?)*\\\\d+\\\\d+(\\\\.\\\\d+)* (如果这看起来更合乎逻辑)

Test测试

for (String test : asList("1.3.164.1.2583.15.46",
    "546.598.856.1.68.268.695.5955565", "5..........", "...56.5656"))
    System.out.println(test.matches("\\d+(\\.\\d+)*"));

produces:产生:

true
true
false
false

我在这里考虑递归正则表达式,我的模式是:

pattern = "\\d+.\\d+(?:.\\d+.\\d+)*"

This one [0-9]+([.][0-9]+)* equivalent to \\\\d+([.]\\\\d+)* is valid for这个[0-9]+([.][0-9]+)* equivalent to \\\\d+([.]\\\\d+)*

1.3.164.1.2583.15.46 , 546.598.856.1.68.268.695.5955565 and 5465988561682686955955565 1.3.164.1.2583.15.46,546.598.856.1.68.268.695.59555655465988561682686955955565

And this one [0-9]+([.][0-9]+)+ equivalent to \\\\d+([.]\\\\d+)+ is valid for而这个[0-9]+([.][0-9]+)+ equivalent to \\\\d+([.]\\\\d+)+

1.3.164.1.2583.15.46 and 546.598.856.1.68.268.695.5955565 but not for 5465988561682686955955565 1.3.164.1.2583.15.46 和 546.598.856.1.68.268.695.5955565但不适用于5465988561682686955955565

You could match with the following regular expression.您可以匹配以下正则表达式。

(?<![.\d])\d+(?:\.\d+)+(?![.\d])

Start your engine!启动你的引擎!

The negative lookarounds are to avoid matching .1.3.164.1 and 1.3.164.1.消极的.1.3.164.1是为了避免匹配.1.3.164.11.3.164.1. . . Including \\d in the lookarounds is to avoid matching 1.3.16 in 1.3.164.1.1.3.164.1.包含\\d是为了避免在1.3.164.1.匹配1.3.16 1.3.164.1. . .

Java's regex engine performs the following operations. Java 的正则表达式引擎执行以下操作。

(?<![.\d])  : negative lookbehind asserts following character is not
              preceded by a '.' or digit
\d+         : match 1+ digits
(?:\.\d+)   : match '.' then 1+ digits in a non-capture group
+           : match the non-capture group 1+ times
(?![.\d])   : negative lookahead asserts preceding character is not
              followed by a '.' or digit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM