【问题标题】:using java , what are the methods to find a word inside a string?使用 java ,有哪些方法可以在字符串中查找单词?
【发布时间】:2011-07-23 18:11:29
【问题描述】:

如果我有一个字符串 str 是:a>b
查找字符串 str 是否具有 > 的最佳方法是什么?我使用:

delimiter =">"
str.split(delimter)


str.contains(">")

还是正则表达式?其实我更喜欢使用正则表达式,在这种情况下如何使用正则表达式?

感谢您的帮助

【问题讨论】:

    标签: java regex pattern-matching string-matching


    【解决方案1】:

    应该是

    System.out.println("a>b".matches(".*>.*"));
    

    但在这种情况下,我会选择contains

    【讨论】:

    • 我认为你的意思是 m.find()。仅当 whole 字符串与您的正则表达式模式匹配时,m.matches 才返回 true(在您的示例中, b 为 false)。
    • 好的,我正在纠正它。因为你只想知道有没有。
    【解决方案2】:

    这很容易。实际上,您不需要把整个 Pattern 定义搞得一团糟。你可以只调用matches。

    str.matches(".*>.*");
    

    【讨论】:

      【解决方案3】:

      String.indexOf()返回指定字符或子字符串第一次出现在字符串中的索引

      你也可以使用

      String.contains() 检查字符串是否包含指定的 char 值序列

      【讨论】:

        【解决方案4】:

        您可以使用 indexOf(int ch) 函数(在 java.lang.String 中找到)。它返回字符串中字符的位置或失败时返回 -1。 示例:

        String s="a>b";
        if(s.indexOf('>')!=-1) {
           System.out.println("> is in there");
        }
        

        注意:它搜索第一次出现的字符或子字符串。

        【讨论】:

          【解决方案5】:

          我认为你不应该在这里使用正则表达式。但是如果你想使用它,你可以试试这个功能。

          private int getWordCount(String word,String source){
                  int count = 0;
                  {
                      Pattern p = Pattern.compile(word);
                      Matcher m = p.matcher(source);
                      while(m.find()) count++;
                  }
                  return count;
              }
          

          你可以调用 if(getWordCount(">","a>b")>0) S.o.p("String contains >");

          谢谢,

          Mayur Shah (www.MayurShah.in)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-12-16
            • 1970-01-01
            • 1970-01-01
            • 2015-12-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多