2016-11-24 128 views
3

我試圖達到一個要求。匹配傳入的字符串與查找字符串

我收到的文件和每個文件都包含一些祕密信息的前50個字符。

例如它我輸入文件字符串

String input = "Check  this  answer and you can find the keyword with this code"; 

然後我就一個查找文件下方

查找字符串

this answer|Do this 
not answer|Do that 
example yes|Dont do 

我想匹配我的祕密信息這可能是當前給定在前50個字符中使用查找字符串。 就像在我的例子「這個答案」在查找字符串與「這個答案」相匹配,但空間在那裏。

所以價值在那裏,但有額外的空間。這不是問題。信息在那裏很重要。所以這是一場比賽

在信息匹配後,我將使用查找字符串中的動作信息。在這個例子中就像是「這樣做」

如何使用java或正則表達式來進行這種匹配?

我已經嘗試過使用包含java的函數,但沒有得到我正在尋找。

預先感謝所有的建議

+0

你問題提到了Java,但你已經用JavaScript標記了它。我猜根據'string',這應該是一個Java問題,所以我已經重新簽名了。 –

回答

0

從你的字符串中的空格或在您的查詢串詞之間加"\s*"

0

一種方法是將表達式中的所有空格替換爲\s+表示至少一個空格字符,然後您將得到正則表達式。

例如:

String input = ... 
// Replace all spaces with \s+ an compile the resulting regular expression 
Pattern pattern = Pattern.compile("this answer".replace(" ", "\\s+")); 
Matcher matcher = pattern.matcher(input); 
// Find a match 
if (matcher.find()) { 
    // Do something 
} 
0

我會做這樣的事情:

String input = "Check  this  answer and you can find the keyword with this code"; 
Map<String, String> lookup = new HashMap<String, String>(); 
lookup.put(".*this\\s+answer.+", "Do this"); 
lookup.put(".*not\\s+answer.+", "Do that"); 
lookup.put(".*example\\s+yes.+", "Dont do"); 

for (String regexKey : lookup.keySet()) { 
    if (input.matches(regexKey)) { 
     System.out.println(lookup.get(regexKey)); 
    } 
} 

或者以確保比賽是在第50個字符:

String input = "Check  this  answer and you can find the keyword with this code"; 
Map<String, String> lookup = new HashMap<String, String>(); 
// Match with^from beginning of string and by placing parentheses we can measure the matched string when match is found. 
lookup.put("(^.*this\\s+answer).*", "Do this"); 
lookup.put("(^.*not\\s+answer).*", "Do that"); 
lookup.put("(^.*example\\s+yes).*", "Dont do"); 


for (String regexKey : lookup.keySet()) { 
    Matcher matchRegexKey = Pattern.compile(regexKey).matcher(input); 
    if (matchRegexKey.matches()) { 
     // Check match is in first 50 chars. 
     if (matchRegexKey.group(1).length() <= 50) { 
      System.out.println(lookup.get(regexKey)); 
     } 
    } 
}