简体   繁体   English

获取十进制数正则表达式

[英]Get decimal number regular expression

I am trying to create a simple program to practice parsing data. 我正在尝试创建一个简单的程序来练习解析数据。 I'll show you my code then explain what I'm trying to do: 我将向您展示我的代码,然后解释我要做什么:

String data = "<span id=\"yfs_l84_ibm\">176.85</span>";
Pattern pattern = Pattern.compile("\\d+([.]\\d{2})?");
Matcher matcher = pattern.matcher(data);
if (matcher.find())
    System.out.println(matcher.group(1));

All I'm trying to do is print out "176.85." 我要做的就是打印“ 176.85”。 There will always be two numbers after the decimal place, and 1 or more numbers in front of the decimal. 小数点后总是有两个数字,小数点前有1个或多个数字。 I don't need to worry about negative numbers, although it wouldn't hurt if my regular expression handled that. 我不需要担心负数,尽管如果我的正则表达式能够处理负数也不会有任何问题。 My code gets inside the if , but prints null . 我的代码进入if ,但输出null Is something wrong with my regular expression? 我的正则表达式有问题吗? Below are other regular expressions I have tried. 以下是我尝试过的其他正则表达式。 They also print null , or never get inside the if . 它们还会输出null ,或者永远不会进入if

  1. ^[+-]?(\\d+(.?\\d+)?|.\\d+)$ ^ [+ - ]?(\\ d +(\\ d +)?|?\\ d +)$
  2. /^\\d+.?\\d*$/ /^\\d+.?\\d*$/
  3. /\\d+.?\\d*/ /\\d+.?\\d*/

If you wish to match numbers with the +/- as a prefix, use: 如果要匹配以+/-为前缀的数字,请使用:

[-+]?\\d{1,4}\\.\\d{2}

And extract group 0. 并提取组0。

Umm, try to change the pattern into this \\\\d+\\\\.\\\\d{2} 嗯,尝试将模式更改为此\\\\d+\\\\.\\\\d{2}
And matcher.group(0) matcher.group(0)
I've tried it and it worked well :) 我试过了,效果很好:)

其表达功能:

(\\d+([.]\\d{2})?)

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

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