java 正则表达式查找浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6754552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to find a float
提问by Jdban101
I've never used regex before, but this java function requires it (shown here: How to set Edittext view allow only two numeric values and two decimal values like ##.##)
我以前从未使用过正则表达式,但是这个 java 函数需要它(如下所示:如何设置 Edittext 视图只允许两个数值和两个十进制值,如 ##.##)
I basically just need to get a float from it the text box, should be simple. I used a tool and it said this should work:
我基本上只需要从中获取一个浮动文本框,应该很简单。我使用了一个工具,它说这应该有效:
String re1="([+-]?\d*\.\d+)(?![-+0-9\.])";
But it doesn't seem to be working, it doesn't let me put anything in the text box.
但它似乎不起作用,它不允许我在文本框中输入任何内容。
What's the right way to do this? Thanks
这样做的正确方法是什么?谢谢
回答by Paul
Try this:
试试这个:
String re1="^([+-]?\d*\.?\d*)$";
回答by Voo
The right way for this problem isn't to use a regex, but just to use:
这个问题的正确方法不是使用正则表达式,而只是使用:
try {
Float.parseFloat(string)
return true;
}
catch (NumberFormatException ex) {
return false;
}
Works perfectly fine, is the same code that is later used to parse the float and therefore bug free (or if it isn't we have a much bigger problem at hand).
工作得很好,是稍后用于解析浮点数的相同代码,因此没有错误(或者如果不是,我们手头有更大的问题)。
回答by Jeff Holt
After balking at the accepted answer (and the other two relevant ones), I decided to provide a new one. Then I found Christoffer Hammarstr?m's Sep 1 '16 at 8:40 mostly hidden comment on Paulpro's answer (which was accepted).
在对接受的答案(以及其他两个相关的答案)犹豫不决之后,我决定提供一个新的答案。然后我发现 Christoffer Hammarstr?m 于 2016 年 9 月 1 日 8:40 发表了对 Paulpro 回答(已被接受)的大部分隐藏评论。
Here's the accepted answer:
这是公认的答案:
String re1="^([+-]?\d*\.?\d*)$";
String re1="^([+-]?\d*\.?\d*)$";
Here's Christoffer's comment:
这是克里斯托弗的评论:
This matches the empty string, or a single dot, or a plus or a minus by itself.
这匹配空字符串,或单个点,或单独的加号或减号。
In fact, none of the 3 answers that adhere to the requirement of the OP do a good job, which is that he must provide an RE to some other class object and allow an end user to type in any valid floating point number.
事实上,符合 OP 要求的 3 个答案中没有一个做得很好,即他必须向其他一些类对象提供 RE 并允许最终用户输入任何有效的浮点数。
Here is my case for a new answer.
这是我的新答案案例。
In summary, my answer is [+-]?(\d+|\d+\.\d+|\.\d+|\d+\.)([eE]\d+)?
. You must add ^
at the beginning and $
at the end the expression if the class object might otherwise give a pass to invalid leading or trailing characters.
总之,我的答案是[+-]?(\d+|\d+\.\d+|\.\d+|\d+\.)([eE]\d+)?
。如果类对象可能会传递无效的前导或尾随字符^
,则必须在$
表达式的开头和结尾添加。
Here's how I read the expression as written above:
下面是我如何阅读上面写的表达式:
[+-]?
[+-]?
This means a leading sign character is allowed but not required.
这意味着允许但不是必需的前导符号字符。
( \d+ | \d+\.\d+ | \.\d+ | \d+\. )
( \d+ | \d+\.\d+ | \.\d+ | \d+\. )
I've added whitespace to make it easier to see what's going on. This means accept the 4 forms of commonly accepted expressions of signless non-scientific-notation floating point numbers. Many computer languages allow for all four. Perhaps with more grouping, this part of the expression could be compressed but at the expense of readability.
我添加了空格,以便更轻松地查看正在发生的事情。这意味着接受 4 种普遍接受的无符号非科学记数法浮点数表达式。许多计算机语言都允许使用这四种语言。也许通过更多的分组,这部分表达式可以被压缩,但以牺牲可读性为代价。
([eE]\d+)?
([eE]\d+)?
This final part means a scientific notation suffix is allowed by not required.
这最后一部分意味着不需要科学记数法后缀。
Here's all the code.
这是所有代码。
$ cat Tester.java | sed 's/^/ /'
import java.util.*;
import java.util.regex.*;
public class Tester {
private class TestVal {
private String val;
private boolean accepted;
private boolean expect;
private boolean tested;
public TestVal (String testValue, boolean expectedResult) {
val = testValue;
expect = expectedResult;
reset();
}
public String getValue () { return val; }
public boolean getExpect () { return expect; }
public void reset () { tested = false; accepted = false; }
public boolean getAccepted () { return accepted; }
public boolean getTested () { return tested; }
public void setAccepted (boolean newAccept) { tested = true; accepted = newAccept; }
}
private ArrayList<TestVal> tests = new ArrayList<TestVal>();
public void doRETest (Pattern re, TestVal tv) {
boolean matches = re.matcher(tv.getValue()).matches();
boolean ok = matches == tv.getExpect();
String result = ok ? "success" : "fail";
System.out.println(String.format("%10s matches=%5s: %s", tv.getValue(), matches, result));
tv.setAccepted(ok);
}
private void testsSummary () {
int skipped = 0;
int passes = 0;
int failures = 0;
for (TestVal tv : tests)
if (tv.getTested())
if (tv.getAccepted())
passes++;
else
failures++;
else
skipped++;
System.out.println(String.format("\npassed %d tests, failed %d tests, and %d tests skipped\n\n", passes, failures, skipped));
}
public void doRETests (String re) {
Pattern p = Pattern.compile(re);
System.out.println(String.format("testing %s", re));
for (TestVal tv : tests) {
tv.reset();
doRETest(p, tv);
}
testsSummary();
}
public Tester () {
tests.add(new TestVal("1", true));
tests.add(new TestVal(".1", true));
tests.add(new TestVal("1.", true));
tests.add(new TestVal("1.0", true));
tests.add(new TestVal("+1", true));
tests.add(new TestVal("+.1", true));
tests.add(new TestVal("+1.", true));
tests.add(new TestVal("+1.0", true));
tests.add(new TestVal("-1", true));
tests.add(new TestVal("-.1", true));
tests.add(new TestVal("-1.", true));
tests.add(new TestVal("-1.0", true));
tests.add(new TestVal("1e2", true));
tests.add(new TestVal(".1e2", true));
tests.add(new TestVal("1.e2", true));
tests.add(new TestVal("1.0e2", true));
tests.add(new TestVal("1.0e2.3", false));
tests.add(new TestVal(".", false));
tests.add(new TestVal("", false));
tests.add(new TestVal("+", false));
tests.add(new TestVal("-", false));
tests.add(new TestVal("a", false));
}
public static void main (String args[]) {
Tester t = new Tester();
String paulpro = "^([+-]?\d*\.?\d*)$";
String lucac = "^([+-]?(\d+\.)?\d+)$";
String armaj = "\d+\.\d+";
String j6t7 = "[+-]?(\d+|\d+\.\d+|\.\d+|\d+\.)([eE]\d+)?";
t.doRETests(paulpro);
t.doRETests(lucac);
t.doRETests(armaj);
t.doRETests(j6t7);
}
}
And here's what happened when I executed it.
这就是我执行它时发生的事情。
$ javac Tester.java && java Tester | sed 's/^/ /'
testing ^([+-]?\d*\.?\d*)$
1 matches= true: success
.1 matches= true: success
1. matches= true: success
1.0 matches= true: success
+1 matches= true: success
+.1 matches= true: success
+1. matches= true: success
+1.0 matches= true: success
-1 matches= true: success
-.1 matches= true: success
-1. matches= true: success
-1.0 matches= true: success
1e2 matches=false: fail
.1e2 matches=false: fail
1.e2 matches=false: fail
1.0e2 matches=false: fail
1.0e2.3 matches=false: success
. matches= true: fail
matches= true: fail
+ matches= true: fail
- matches= true: fail
a matches=false: success
passed 14 tests, failed 8 tests, and 0 tests skipped
testing ^([+-]?(\d+\.)?\d+)$
1 matches= true: success
.1 matches=false: fail
1. matches=false: fail
1.0 matches= true: success
+1 matches= true: success
+.1 matches=false: fail
+1. matches=false: fail
+1.0 matches= true: success
-1 matches= true: success
-.1 matches=false: fail
-1. matches=false: fail
-1.0 matches= true: success
1e2 matches=false: fail
.1e2 matches=false: fail
1.e2 matches=false: fail
1.0e2 matches=false: fail
1.0e2.3 matches=false: success
. matches=false: success
matches=false: success
+ matches=false: success
- matches=false: success
a matches=false: success
passed 12 tests, failed 10 tests, and 0 tests skipped
testing \d+\.\d+
1 matches=false: fail
.1 matches=false: fail
1. matches=false: fail
1.0 matches= true: success
+1 matches=false: fail
+.1 matches=false: fail
+1. matches=false: fail
+1.0 matches=false: fail
-1 matches=false: fail
-.1 matches=false: fail
-1. matches=false: fail
-1.0 matches=false: fail
1e2 matches=false: fail
.1e2 matches=false: fail
1.e2 matches=false: fail
1.0e2 matches=false: fail
1.0e2.3 matches=false: success
. matches=false: success
matches=false: success
+ matches=false: success
- matches=false: success
a matches=false: success
passed 7 tests, failed 15 tests, and 0 tests skipped
testing [+-]?(\d+|\d+\.\d+|\.\d+|\d+\.)([eE]\d+)?
1 matches= true: success
.1 matches= true: success
1. matches= true: success
1.0 matches= true: success
+1 matches= true: success
+.1 matches= true: success
+1. matches= true: success
+1.0 matches= true: success
-1 matches= true: success
-.1 matches= true: success
-1. matches= true: success
-1.0 matches= true: success
1e2 matches= true: success
.1e2 matches= true: success
1.e2 matches= true: success
1.0e2 matches= true: success
1.0e2.3 matches=false: success
. matches=false: success
matches=false: success
+ matches=false: success
- matches=false: success
a matches=false: success
passed 22 tests, failed 0 tests, and 0 tests skipped
回答by Luca C.
This is the correct way:
这是正确的方法:
String floatRegexp="^([+-]?(\d+\.)?\d+)$";
or if you look also in the middle of other text:
或者如果您也在其他文本的中间查看:
String floatRegexp="([+-]?(\d+\.)?\d+)";
and if you don't look for the minus/plus sign:
如果您不寻找减号/加号:
String floatRegexp="^(\d+\.)?\d+$";
回答by Ar maj
this answer is from Johan Sj?berg https://stackoverflow.com/a/12235002/4035655
这个答案来自 Johan Sj?berg https://stackoverflow.com/a/12235002/4035655
You could try matching the digits using a regular expression
您可以尝试使用正则表达式匹配数字
\d+\.\d+
This could look something like
这可能看起来像
Pattern p = Pattern.compile("\d+\.\d+");
Matcher m = p.matcher("Sstring>26.0.[2.3.2.3D] .352.(f) 1)"503B"(.67>>Sstring");
while (m.find()) {
System.out.println(Float.parseFloat(m.group()));
}
the output is:
输出是:
26.0
2.3
2.4
1.67
the part [2.3.2.3D]
of the string is split into two separate float numbers
[2.3.2.3D]
字符串的一部分被分成两个单独的浮点数
回答by N Djel Okoye
String floatRegex = "[+-]?\d*([.]?\d+)";