2017-05-25 69 views
0
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任何一個出現時,它return True 能否請你幫我寫Reguler它的工作表達式

回答

0

你的問題不是很清楚,但基本上你不需要正則表達式來檢查是否在另一個字符串的子串,你可以只使用

boolean isSubstring = t1.contains(t2); 

如果t2確實是一個正則表達式,不是一個普通的字符串,你需要創建一個從它Pattern對象(像你一樣),然後創建您要檢查的字符串Matcher,然後用Matcher.find()方法檢查

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

你並不需要使用正則表達式,你可以只需使用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. 檢查,如果你的字符串包含所有這些結果,如果一個不存在打破你的循環並返回假
相關問題