Java 如何使用正则表达式查找子字符串

Java 如何使用正则表达式查找子字符串,java,regex,Java,Regex,我试试这个 t1 Hello world t2:Hello t2 :wo t2:rl t2:Hello world t1 returns all this 3 but i want only hello or world key 但是如果t2包含Helow-world 我想要Hello或world任何人在场它返回True 你能帮我写正则表达式吗?你的问题不是很清楚,但基本上你不需要正则表达式来检查一个字符串的子字符串是否在另一个字符串中,你只需要使用 Pattern p1 = Pattern

我试试这个

t1 Hello world
t2:Hello
t2 :wo
t2:rl
t2:Hello world
t1 returns all this 3 but i want only hello or world key 
但是如果
t2
包含
Helow-world
我想要
Hello或world
任何人在场它
返回True

你能帮我写正则表达式吗?你的问题不是很清楚,但基本上你不需要正则表达式来检查一个字符串的子字符串是否在另一个字符串中,你只需要使用

Pattern p1 = Pattern.compile("^"+t1+"$");
Pattern p2 = Pattern.compile("^"+t2+"$");
return  p1.toString().contains(p2.toString());
如果
t2
确实是一个正则表达式,而不是一个正则字符串,则需要从中创建一个
模式
对象(正如您所做的那样),然后在要检查的字符串上创建一个
匹配器
,然后使用
Matcher.find()方法进行检查

boolean isSubstring = t1.contains(t2);

您不需要使用正则表达式,只需使用String::contains方法即可,下面是一个简单的示例:

Pattern p = Pattern.compile(t2);
Matcher m = p.matcher(t1);
boolean isSubstring = m.find();

这个想法是:

  • 用空格分隔你的单词
  • 循环抛出这个结果
  • 检查your字符串是否包含所有这些结果,如果不存在,则中断循环并返回false
  • Pattern p = Pattern.compile(t2);
    Matcher m = p.matcher(t1);
    boolean isSubstring = m.find();
    
    String line = "Hellow My best world of java";
    String str = "Hello world";
    String[] spl = str.replaceAll("\\s+", " ").split(" ");
    boolean check = true;
    for(String s : spl){
        if(!line.contains(s)){
            check = false;
            break;
        }
    }
    System.out.println(check ? "Contain all" : "Not contains all");