首页 \ 问答 \ Java - 拆分字符串以获取十进制数(Java - Split String to get decimal number)

Java - 拆分字符串以获取十进制数(Java - Split String to get decimal number)

我需要从网站中提取一些数据,然后在变量中保存一些值。

在这里你有代码:

public class Principal {

 public static void main(String[] args) throws IOException {

    URL url = new URL("http://www.numbeo.com/cost-of-living/country_result.jsp?country=Turkey");
    URLConnection yc = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
            String valor;
            String str = null;

    while ((inputLine = in.readLine()) != null) {
                    if(inputLine.contains("Milk"))
                    {
                         System.out.println("Encontrei! " + inputLine );
                         valor=inputLine.substring(inputLine.lastIndexOf("\"priceValue\">") + 14);
                         System.out.println("valor:" +valor);

                    }

            }
    in.close();
    }

  }

第一个输入行打印: <tr class="tr_standard"><td>Milk (regular), (1 liter) </td> <td style="text-align: right" class="priceValue"> 2.45&nbsp;TL</td>

现在我必须提取"2.45"我该怎么做? 我已经尝试了一些正则表达式,但无法使它工作。 对不起我的英语不好。 提前致谢。


I need to extract some data from an website and then save some values in variables.

Here you've got the code:

public class Principal {

 public static void main(String[] args) throws IOException {

    URL url = new URL("http://www.numbeo.com/cost-of-living/country_result.jsp?country=Turkey");
    URLConnection yc = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
            String valor;
            String str = null;

    while ((inputLine = in.readLine()) != null) {
                    if(inputLine.contains("Milk"))
                    {
                         System.out.println("Encontrei! " + inputLine );
                         valor=inputLine.substring(inputLine.lastIndexOf("\"priceValue\">") + 14);
                         System.out.println("valor:" +valor);

                    }

            }
    in.close();
    }

  }

First inputline print this: <tr class="tr_standard"><td>Milk (regular), (1 liter) </td> <td style="text-align: right" class="priceValue"> 2.45&nbsp;TL</td>

Now I've got to extract just the "2.45" how can I do that? I already tried with some Regex but can't make it work. Sorry for my English. Thanks in advance.


原文:https://stackoverflow.com/questions/33767996
更新时间:2022-03-03 21:03

最满意答案

C ++ 11标准(我相信它添加了snprintf)有什么可说的吗?

是的,您描述的行为对于snprintf是正确的。 在C标准之后(由C ++标准引用):

(7.21.6.5.3。) snprintf函数返回已经写入的字符n已足够大,不计算终止空字符, 如果发生编码错误则返回负值 。 因此,当且仅当返回值是非负且小于n时,才完全写入以null结尾的输出。

至于errno - 功能描述没有说明,所以这适用:

(7.5.3。)如果在本国际标准的功能描述中没有记录errno的使用,则可以通过库函数调用将errno的值设置为非零值,无论是否存在错误。


Does the C++11 standard (which I believe adds snprintf) have anything to say about this?

Yes, the behaviour you described would be correct for snprintf. After the C standard (referred to by C++ standard):

(7.21.6.5.3.) The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

As for the errno - the function description says nothing about it, so this applies:

(7.5.3.) The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard.

相关问答

更多
  • POSIX没有定义free设置errno (虽然POSIX目前不禁止它,所以实现可能会这样做 - 参考@ ArjunShankar的答案更多的细节)。 但这与您的关注并不重要。 检查错误的方式不正确。 您应该检查fputs的返回值,并检查它是否小于0 。 如果是,那么您可以检查errno以了解导致失败的原因,但这是可选的(应该在调用任何其他功能之前完成)。 所以,这样的事情应该做的诀窍: int result = fputs(buf, somefile); /* optionally read errno ...
  • 我找到了一个可能不太理想的解决方案,但它确实允许在Visual Studio 2015中构建解决方案而不会出错。 在项目属性中,我将“Platform Toolset”设置为来自VS 2013的旧版v120_xp(VS 2015提供v140_xp)。 这远非完美,因为它需要VS 2013与VS 2015一起安装,显然我无法利用v140平台工具集中的任何新功能。 I found a solution to this which might not be ideal, but it does allow the ...
  • std::ostringstream是使用snprintf的替代方法: char buf[1024]; snprintf(buf, 1024, "%d%s", 4, "hello"); 当量: #include std::ostringstream s; s << 4 << "hello"; // s.str().c_str(); // This returns `const char*` to constructed string. 还有boost :: lexical_cast ...
  • 对于许多微控制器,可以使用没有浮动/双重支持的简化printf功能。 例如,许多平台都有newlib nano和texas仪器提供ustdlib.c 。 使用其中一个非浮动printf函数,您可以只使用整数将打印拆分为某些内容 float a = -1.2339f; float b = a + ((a > 0) ? 0.0005f : -0.0005f); int c = b; int d = (int)(b * 1000) % 1000; if (d < 0) d = -d; printf("%d.%03 ...
  • 是的,有sscanf() 。 它返回与输入成功匹配的令牌数量,因此您可以检查返回值以查看它到输入字符串中的距离。 if (sscanf(buffer, "Number:%i", &i) == 1) { /* The number was successfully parsed */ } Yes, there is sscanf(). It returns the number of tokens successfully matched to the input, so you can check ...
  • strtol仅为溢出条件设置errno ,而不是指示解析失败。 为此,您必须检查结束指针的值,但是您需要存储指向原始字符串的指针: char const * const str = "blah"; char const * endptr; int n = strtol(str, &endptr, 0); if (endptr == str) { /* no conversion was performed */ } else if (*endptr == '\0') { /* the entire s ...
  • StringBuilder.AppendFormat String.Format是最接近的。 它执行相同的操作,但请注意格式字符串格式不同 。 使用String.Format : string buf = string.Format("{0}", frame); 使用StringBuilder.AppendFormat : StringBuilder builder = new StringBuilder(); builder.AppendFormat("{0}", frame); StringBuil ...
  • 正如WeatherVane指出的那样,这在VS2015中不会发生,并且似乎是VS2013实施中的一个错误。 As WeatherVane has pointed out, this does not occur in VS2015 and appears to be a bug in the VS2013 implementation.
  • 因为snprintf(buf, sizeof buf, "output: %s%s%s"); 需要3个参数: snprintf(buf, sizeof buf, "output: %s%s%s", str1, str2, str3); 和snprintf(buf, sizeof buf, "output: %s%s"); 需要2个参数: snprintf(buf, sizeof buf, "output: %s%s", str1, str2); 如果你没有将参数传递给snprintf函数并不意味着snpri ...
  • C ++ 11标准(我相信它添加了snprintf)有什么可说的吗? 是的,您描述的行为对于snprintf是正确的。 在C标准之后(由C ++标准引用): (7.21.6.5.3。) snprintf函数返回已经写入的字符n已足够大,不计算终止空字符, 如果发生编码错误则返回负值 。 因此,当且仅当返回值是非负且小于n时,才完全写入以null结尾的输出。 至于errno - 功能描述没有说明,所以这适用: (7.5.3。)如果在本国际标准的功能描述中没有记录errno的使用,则可以通过库函数调用将errn ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)