【问题标题】:Java - Comparing stringsJava - 比较字符串
【发布时间】:2013-04-08 09:39:45
【问题描述】:

我正在尝试从缓冲阅读器中检查字符串值是否与浏览器中的用户输入匹配。如果用户输入 localhost:9999/getMusic 数据输出正常,但是我试图确保只有 /getMusic 或 /getMusic= 被传递,而不是给出我制作的 404 错误页面。现在,如果我输入 /getSomething,我只能得到 404。

如果我输入例如 /getMusicc(最后有两个 c),我希望它也给我一个 404,但它不会给我。我意识到它是因为 .contains 方法,但我不知道还能使用什么。基本上我需要与我指定的内容匹配的确切字符串值。我尝试使用 .contentsEqual 没有运气。

String line = reader.readLine();
        if(line !=null){
        System.out.println("[CLIENT] " + soc.getInetAddress().getHostName() 
                + " - " + soc.getInetAddress().getHostAddress() + " requesting: " + line);

        //the first line should be: GET /path HTTP/1.1
        if (line.startsWith("GET ")&& (line.endsWith("HTTP/1.0")||line.endsWith("HTTP/1.1"))){
            String path = line;//check this

            OutputStream output = soc.getOutputStream();
//here is my problem below...
            if(path.contains("/getMusic") || path.contains("/getMusic=")){
                String type = "";

                if (path.contains("/getMusic=rap")){
                    type = "Rap";
                }

我应该补充一点,这个字符串有几个词长,我要测试的值在所有这些词的中间。即 GET /getMusic HTTP1.1。只应测试 /getMusic。

在第一级上运行良好,但是如果我想测试 /getMusic=rap 就不行了。

  if(path.matches(".*/getMusic=?(\\s+.*)?")){
                String type = "";


                if(path.matches(".*/getMusic=rap")){
                    type = "Rap";
                }

【问题讨论】:

  • 我不知道如何使用正则表达式,你能举个例子吗?
  • @GSZingh:请参阅下面关于使用正则表达式验证输入的答案。
  • 看看这个gskinner.com/RegExr

标签: java string testing bufferedreader string-comparison


【解决方案1】:

代替:

if(path.contains("/getMusic") || path.contains("/getMusic="))

你应该使用:

if(path.matches("^.*?/getMusic=?.*$"))

【讨论】:

    【解决方案2】:

    一个简单的解决方案是使用正则表达式来测试字符串的结尾。比如:

    If(str.matches(".*/getMusic=?$")) {}
    

    这将测试任何东西都可以出现在短语'/getMusic'之前,但之后什么都不能出现!

    【讨论】:

      【解决方案3】:

      你可以使用

      if(path.matches(".*/getMusic=?(\\s+.*)?"))

      基本上是做什么的

      .* - 要测试的字符串之前的任何内容
      /getMusic - 你知道这是什么
      =? - 检查“=”是否可选存在
      (\s+.*)? - 如果它可选地包含一个或多个空格 + 空格后的任何内容

      【讨论】:

      • 在第一级上运行良好,但是如果我想测试 /getMusic=rap 它就行不通。 if(path.matches(".*/getMusic=?(\\s+.*)?")){ String type = ""; if(path.matches(".*/getMusic=rap")){ type = "Rap"; }
      猜你喜欢
      • 2014-11-11
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多