Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java,在字符串中查找单词的方法有哪些?_Java_Regex_Pattern Matching_String Matching - Fatal编程技术网

使用java,在字符串中查找单词的方法有哪些?

使用java,在字符串中查找单词的方法有哪些?,java,regex,pattern-matching,string-matching,Java,Regex,Pattern Matching,String Matching,如果我有一个字符串str,它是:a>b 查找字符串str是否有的最佳方法是什么?我是否使用: 分隔符=“>” str.split(delimter) 或 str.contains(“>”) 还是正则表达式?实际上我更喜欢使用正则表达式,在这种情况下如何使用正则表达式 谢谢你的帮助那太好了 System.out.println("a>b".matches(".*>.*")); 但是在这种情况下,我会选择contains这个很简单。实际上,您不需要把整个模式定义搞得一团糟。你可以叫火柴

如果我有一个字符串str,它是:
a>b

查找字符串str是否有
的最佳方法是什么?我是否使用:

分隔符=“>”

str.split(delimter)


str.contains(“>”)

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

谢谢你的帮助

那太好了

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

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

这个很简单。实际上,您不需要把整个模式定义搞得一团糟。你可以叫火柴

str.matches(".*>.*");
String.indexOf()
返回指定字符或子字符串第一次出现的字符串内的索引

你也可以使用

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

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


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

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

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(“字符串包含>”

谢谢


Mayur Shah()

我想你指的是m.find()。m、 matches仅当整个字符串与您的正则表达式模式匹配时才返回true(在您的示例中,b为false)。因为你只想知道有没有。
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;
    }