Java 如何匹配URL中的单词(字符串)

Java 如何匹配URL中的单词(字符串),java,regex,url,pattern-matching,string-matching,Java,Regex,Url,Pattern Matching,String Matching,这个网站包含不同的网址,但我想我的应用程序应该vist网址只包含像“药物”这样的特定关键字 如果URL是 它应该访问第一个URL。所以如何在URL中匹配特定的关键字drug。我知道它也可以使用regexp完成,但我是新手 我在这里使用Java您可以使用方法contains()检查字符串是否包含单词。 if(myString.contains(“药物”)) 如果您只需要包含/drug/的URL,请尝试执行以下操作: Pattern p = Pattern.compile("/drug(

这个网站包含不同的网址,但我想我的应用程序应该vist网址只包含像“药物”这样的特定关键字 如果URL是

它应该访问第一个URL。所以如何在URL中匹配特定的关键字drug。我知道它也可以使用regexp完成,但我是新手
我在这里使用Java

您可以使用方法contains()检查字符串是否包含单词。
if(myString.contains(“药物”))

如果您只需要包含/drug/的URL,请尝试执行以下操作:

    Pattern p = Pattern.compile("/drug(/|$)");
    Matcher m = p.matcher(myURLString);
    if(m.find())
    {
        something_to_do
    }
(/|$)
意味着
/drug
之后只能是斜杠(/)或什么都不能(dollar表示行尾)。因此,如果字符串类似于
../drug/../code>或
../drug
使用
拆分()
,则此正则表达式将查找所有内容:

final String[] words = input.replaceFirst("https?://", "").split("/+");
for (final String word: words)
    if ("whatyouwant".equals(word))
       //do what is necessary since the word matches

如果您的代码经常被调用,您可能希望使用
https?://
/+
创建
模式
s,并使用
匹配器
s。

使用字符串类的Contains()方法。问题是它也会匹配,比如说,
drugestore