【问题标题】:search string value with wild card in another string java [duplicate]在另一个字符串java中使用通配符搜索字符串值[重复]
【发布时间】:2016-09-25 18:50:57
【问题描述】:

假设我有字符串值

String strValue1 = "This is the 3TB value"; 
String strValue2 = "3TB is the value"; 
String strValue3 = "The value is 3TB";

不,当用户搜索3TB* 时,它应该与strValue2 匹配,就像用户搜索*3TB* 时一样,它应该与strValue1 匹配,而对于*3TB,它应该与strValue3 匹配

我尝试了很多示例,但没有运气。是否有任何通配符搜索字符串?我不能使用任何外部库

【问题讨论】:

  • 你听说过正则表达式吗??
  • 是的,我也试过了。但似乎这在我的情况下不起作用:(
  • “但在我的情况下似乎不起作用”您应该展示您尝试过的内容,因为可以使用正则表达式。

标签: java string-matching


【解决方案1】:

您可能正在寻找Regular Expressions

既然你说你不能使用外部库,我认为这可能是家庭作业,所以我不会直接回答在这种情况下如何使用它们。

【讨论】:

    【解决方案2】:

    您可以使用以下命令检查3TB* 案例:

    str.startsWith("3TB")
    

    其中str 是您正在检查匹配的字符串。

    您可以使用以下命令检查*3TB* 的情况:

    str.contains("3TB")
    

    【讨论】:

      【解决方案3】:

      如果您能够在搜索中将通配符 * 替换为 .+。下面的 sn-p 可以作为一个起点。

      String[] strings = {"This is the 3TB value", "3TB is the value", 
                          "The value is 3TB"};
      String[] pattern = {"3TB.+", ".+3TB.+", ".+3TB"};
      for (String s : strings) {
          for (String p : pattern) {
              if (s.matches(p)) {
                  System.out.printf("pattern: %-7s   matches: %s%n", p, s);
              }
          }
      }
      

      输出

      pattern: .+3TB.+   matches: This is the 3TB value
      pattern: 3TB.+     matches: 3TB is the value
      pattern: .+3TB     matches: The value is 3TB
      

      【讨论】:

      • 哇!它的工作..我没想过用.+替换star *这就是我的正则表达式失败的原因我猜..谢谢!
      猜你喜欢
      • 2021-11-28
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多