【问题标题】:find substring ignoring whitespaces查找忽略空格的子字符串
【发布时间】:2015-02-18 06:26:43
【问题描述】:

我想搜索忽略空格的 java 字符串。例如

abc    cdf   sdf
abc cdf   sdf
abc        cdf     sdf

什么应该是可能的搜索关键字,可以是正则表达式。

如果我要搜索上面的字符串

abc cdf sdf

这将不匹配。

【问题讨论】:

  • 那么,您要搜索什么?举个例子。到目前为止,您尝试过什么?在问题中包含您的代码,以便我们告诉您问题出在哪里

标签: java string search


【解决方案1】:

根据其他规则,这可能是您的起点。

String s = "abc        cdf     sdf";
System.out.println(s.matches("abc\\s*cdf\\s*sdf"));

对于正则表达式,请查看教程http://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html

【讨论】:

    【解决方案2】:

    制作一个没有空格的临时新字符串并使用正常方式在其中搜索,..

    【讨论】:

      【解决方案3】:

      这是解决问题的简单方法。

      首先,从字符串中删除空格并使用 indexOf 方法进行搜索。
      希望这种方法对您有所帮助。

      试试下面的代码:

      package com.stackoverflow;
      
          import java.io.IOException;
      
          import org.apache.commons.lang.StringUtils;
      
          public class IgnoreWhiteSpace {
      
              public static void main(String[] args) throws IOException {
      
      
                  String search = "abc    cdf   sdf";
      
                  System.out.println(StringUtils.deleteWhitespace(search));
      
                  System.out.print("Found Index :" );
      
                  System.out.println(search.indexOf( 'c' ));
      
              }
      
          }
      

      【讨论】:

      • 您的解决方案也将匹配例如输入字符串“ab ccdfs df”。这不等于请求者的搜索模式“abc def sdf”。
      猜你喜欢
      • 2014-05-29
      • 2011-02-05
      • 1970-01-01
      • 2015-12-17
      • 2014-10-22
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多