匹配传入的字符串与查找字符串
问题描述:
我试图达到一个要求。匹配传入的字符串与查找字符串
我收到的文件和每个文件都包含一些秘密信息的前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的函数,但没有得到我正在寻找。
预先感谢所有的建议
答
从你的字符串中的空格或在您的查询串词之间加"\s*"
。
答
一种方法是将表达式中的所有空格替换为\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
}
答
我会做这样的事情:
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));
}
}
}
你问题提到了Java,但你已经用JavaScript标记了它。我猜根据'string',这应该是一个Java问题,所以我已经重新签名了。 –