繁体   English   中英

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

[英]how to find Sub String Using regular Expression

UDF2<String, String, Boolean> contains = new UDF2<String, String, Boolean>() {
 private static final long serialVersionUID = -5239951370238629896L;
 @Override
     public Boolean call(String t1, String t2) throws Exception {
        Pattern p1 = Pattern.compile(t1);
        Pattern p2 = Pattern.compile(t2);
        return  p1.toString().contains(p2.toString());
     }
 };
 spark.udf().register("contains", contains, DataTypes.BooleanType);

在上面的代码中找到其他字符串中的键,如果找到则return true但它也返回t2子字符串。

实际输出:

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 

我尝试这个

Pattern p1 = Pattern.compile("^"+t1+"$");
Pattern p2 = Pattern.compile("^"+t2+"$");
return  p1.toString().contains(p2.toString());

但是,如果t2包含Helow world我希望Hello OR world任何一个Hello OR world出现,它return True ,请您帮我写Reguler Expression

您的问题不是很清楚,但是基本上不需要正则表达式来检查一个字符串的子字符串是否在另一个字符串中,您可以使用

boolean isSubstring = t1.contains(t2);

如果t2确实是一个正则表达式 ,而不是正则字符串,则需要从中创建一个Pattern对象(如您所做的那样),然后在要检查的字符串上创建一个Matcher ,然后使用Matcher.find()检查方法

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

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

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");

这个想法是:

  1. 用空格分开你的话
  2. 循环抛出此结果
  3. 检查您的字符串是否包含所有这些结果,如果不存在则中断循环并返回false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM