【问题标题】:How to find substring of a string with whitespaces in Java?如何在Java中找到带有空格的字符串的子字符串?
【发布时间】:2012-03-06 19:47:27
【问题描述】:

我想检查字符串是否包含特定的子字符串并使用 CONTAINS() 。

但这里的问题在于空间。

Ex- str1="c not in(5,6)"

我想检查 str 是否包含 NOT IN 所以我使用 str.contains("not in")..

但问题是这里 NOT 和 IN 之间的空格没有确定,即也可以有 5 个空格..

如何解决我可以找到像 not in 这样的子字符串,中间没有任何空格...

【问题讨论】:

  • 看看在Java中使用正则表达式。

标签: java string substring


【解决方案1】:

使用regular expression (Pattern) 获取Matcher 以匹配您的字符串。

正则表达式应该是"not\\s+in"(“not”,后跟一些空格字符,然后是“in”):

public static void main(String[] args) {

    Matcher m = Pattern.compile("not\\s+in").matcher("c not  in(5,6)");

    if (m.find())
        System.out.println("matches");
} 

请注意,有一个名为 matches(String regexp) 的 String 方法。您可以使用正则表达式".*not\\s+in.*" 来获取匹配,但这并不是执行模式匹配的好方法。

【讨论】:

  • 这是有效的,但仍然只是为了知识。有什么方法可以将这些空间减少到 1?
  • str = str.replaceAll("not\\s+in", "not in")
【解决方案2】:

你应该使用regex"not\\s+in"

    String s = "c not  in(5,6)";
    Matcher matcher = Pattern.compile("not\\s+in").matcher(s);
    System.out.println(matcher.find());

解释:\\s+ 表示任何类型的空格 [也可以使用制表符],并且必须至少重复一个 [任何数字 >=1 都可以]。
如果您只想要空格,没有制表符,请将您的正则表达式更改为 "not +in"

【讨论】:

  • 这是有效的,但仍然只是为了知识。有什么方法可以将这些空间减少到 1?
  • @Sam:同样,使用正则表达式:s.replaceAll("\\s+"," ") 会将所有空格替换为一个空格。
【解决方案3】:

使用String.matches() 方法,该方法检查字符串是否匹配正则表达式(docs)。

在你的情况下:

String str1 = "c not in(5,6)";
if (str1.matches(".*not\\s+in.*")) {
    // do something
    // the string contains "not in"
}

【讨论】:

    【解决方案4】:

    不区分大小写:(?i)

    也将换行符视为点.(?s)

    str1.matches("(?is).*not\\s+in.*")
    

    【讨论】:

      【解决方案5】:

      请尝试关注,

      int result = str1.indexOf ( "not in" );
      
      if ( result != -1 ) 
      {
             // It contains "not in" 
      }
      else if ( result == -1 )
      {
           // It does not contain "not in"
      }
      

      【讨论】:

      • 如果“not”和“in”之间有多个空格,这将不起作用。
      • 请看问题,OP表示“not”和“in”之间可能有多个空格
      • 如问题所述,“not”和“in”之间的空格数可能不定。
      【解决方案6】:

      一般你可以这样做:

      if (string.indexOf("substring") > -1)... //It's there
      

      【讨论】:

      • 如何处理“not”和“in”之间可变数量的空格?
      • 您引用了主题,但没有引用问题本身。
      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2016-01-12
      • 2022-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2016-02-23
      相关资源
      最近更新 更多