【问题标题】:How to neglect blank spaces in a string search in html file using java?java - 如何在使用java的html文件中忽略字符串搜索中的空格?
【发布时间】:2016-11-08 16:43:58
【问题描述】:

我有一个 html 文件,我必须逐行搜索并查找特定的字符串,然后采取相应的措施。 问题是字符串与html文件每一行的整行匹配。 因此,如果给定行中的实际字符串之前有一些空格,则匹配结果为假,即使它应该是肯定的。

package read_txt;

import java.io.*;
class FileRead 
{
public static void main(String args[])
{
  try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.html");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
        // Print the content on the console
        //String a = "media query";
        switch (strLine) {
        case "@media query" :
            System.out.println("media query found");
            System.out.println("html file responsive");
            break;
        //  default :
            //  System.out.println("html file unresponsive");
            //break;
        }
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}
}

在上面的代码中,我正在搜索字符串“媒体查询”。现在假设这是正在搜索的 html 文件:

代码对这个 html 文件运行良好,但现在假设我们有这个 html 文件:

虽然存在媒体查询字符串,但字符串匹配不起作用,但如果我将匹配的字符串更改为“媒体查询”而不是“媒体查询”,它会再次起作用。 知道如何忽略在一行中出现任何文本之前出现的空格吗?

【问题讨论】:

  • 看看Stringtrim()方法...
  • 感谢您的建议。会调查的

标签: java string html-parsing string-search


【解决方案1】:

在这种情况下,我认为使用“switch”不是正确的方法。

你可以使用

if (strLine.contains("media query"))

但如果该行有“媒体查询”(两个空格而不是一个),那将失败。 所以,最好的办法是使用正则表达式。

【讨论】:

  • 谢谢 :) 是的,唯一的问题是开头的空格,'media'和'query'之间出现拼写错误或两个空格的概率很低
【解决方案2】:

你可以使用endsWith,例如

if (strLine.endsWith("media query")) { ...

如果搜索到的字符串可能位于行中间的某个位置,您可以使用 indexOf,例如

if (strLine.indexOf("medial quera") >= 0) { ...

【讨论】:

  • 谢谢托马斯,这将是很大的帮助,我可以将这些搜索或这些搜索一起进行防故障匹配! :)
猜你喜欢
  • 1970-01-01
  • 2014-02-17
  • 2022-01-01
  • 2021-04-25
  • 1970-01-01
  • 2011-06-19
  • 2011-12-18
  • 2022-01-02
  • 2018-12-16
相关资源
最近更新 更多